From c627aedcf62dfc2cccf244eabacdab05cd1b5cce Mon Sep 17 00:00:00 2001 From: Luis Fernando Molina Date: Sat, 23 Feb 2019 10:32:06 +0100 Subject: [PATCH] Autoformatter applied on all js files --- Animation.js | 205 ++-- BottomSpace/ChartAspectRatio.js | 173 ++-- BottomSpace/DeleteTradingHistory.js | 407 ++++---- BottomSpace/PlayStopButton.js | 236 ++--- BreakpointsBar.js | 286 +++--- Candle.js | 30 +- Canvas.js | 900 ++++++++--------- ChartUtilities.js | 218 ++-- CloudVM/CloudRequire.js | 88 +- CloudVM/CloudSupport.js | 226 ++--- CloudVM/CloudVM.js | 237 ++--- CloudVM/WebFS.js | 89 +- CompetitionStorage.js | 240 ++--- Container.js | 58 +- Dashboard.js | 291 +++--- Displace.js | 101 +- EventHandler.js | 123 +-- Exchange/ExchangeAPI.js | 245 +++-- Files/DailyFiles.js | 577 +++++------ Files/FileCloud.js | 422 ++++---- Files/FileCursor.js | 1060 +++++++++----------- Files/FileSequence.js | 545 +++++----- Files/MarketFiles.js | 389 ++++---- Files/SingleFile.js | 154 ++- FloatingSpace/FloatingLayer.js | 1438 ++++++++++++--------------- FloatingSpace/FloatingObject.js | 404 ++++---- FloatingSpace/Note.js | 456 ++++----- FloatingSpace/NoteSets.js | 408 ++++---- FloatingSpace/ProfileBall.js | 1 - FloatingSpace/ProfileBalls.js | 102 +- Frame.js | 824 +++++++-------- Globals.js | 2 +- Panels/ProductsPanel.js | 284 +++--- Panels/TimeControlPanel.js | 242 +++-- PlottersManager.js | 1081 +++++++++----------- ProductCard.js | 1263 +++++++++++------------ ProductStorage.js | 753 +++++++------- Scales/ChartGrid.js | 1017 +++++++++---------- Scales/RightScale.js | 91 +- Spaces/BottomSpace.js | 154 ++- Spaces/ChartSpace.js | 153 ++- Spaces/FloatingSpace.js | 50 +- Spaces/PanelsSpace.js | 173 ++-- Spaces/TopSpace.js | 192 ++-- SplashScreen.js | 212 ++-- TimeLineCoordinateSystem.js | 178 ++-- TimeMachine.js | 240 +++-- TimelineChart.js | 690 ++++++------- TopSpace/CompanyLogo.js | 121 ++- TopSpace/CurrentBot.js | 233 ++--- TopSpace/CurrentProcess.js | 214 ++-- TopSpace/CurrentStartMode.js | 178 ++-- TopSpace/DevTeam.js | 200 ++-- TopSpace/EndUser.js | 126 ++- TopSpace/Login.js | 289 +++--- Utilities.js | 169 ++-- ViewPort.js | 687 ++++++------- VolumeBar.js | 20 +- WebDebugLog.js | 34 +- 59 files changed, 9087 insertions(+), 10892 deletions(-) diff --git a/Animation.js b/Animation.js index 7bf5638d3..f79a9a526 100644 --- a/Animation.js +++ b/Animation.js @@ -1,11 +1,10 @@ - -function newAnimation() { - const MODULE_NAME = "Animation"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; +function newAnimation () { + const MODULE_NAME = 'Animation' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME /* @@ -15,157 +14,117 @@ function newAnimation() { */ - let animationLoopHandle; // This is the handle to the animation loop. With this handle we can cancel the loop, for instance. - let callBackFunctions = new Map(); + let animationLoopHandle // This is the handle to the animation loop. With this handle we can cancel the loop, for instance. + let callBackFunctions = new Map() - let thisObject = { - start: start, - stop: stop, - addCallBackFunction: addCallBackFunction, - removeCallBackFunction: removeCallBackFunction, - initialize: initialize - }; + let thisObject = { + start: start, + stop: stop, + addCallBackFunction: addCallBackFunction, + removeCallBackFunction: removeCallBackFunction, + initialize: initialize + } - return thisObject; + return thisObject - function initialize(callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function initialize (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } /* Nothing to do here yet. */ - callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + function start (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] start -> Entering function.') } - function start(callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] start -> Entering function."); } - - animationLoop(); // Inside this function the animation process is started, and at the same time it creates a loop. - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] start -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + animationLoop() // Inside this function the animation process is started, and at the same time it creates a loop. + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] start -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function stop(callBackFunction) { + function stop (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] stop -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] stop -> Entering function."); } - - window.cancelAnimationFrame(animationLoopHandle); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] stop -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + window.cancelAnimationFrame(animationLoopHandle) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] stop -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function addCallBackFunction(key, callBack, callBackFunction) { + function addCallBackFunction (key, callBack, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] addCallBackFunction -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] addCallBackFunction -> Entering function."); } - - callBackFunctions.set(key, callBack); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] addCallBackFunction -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBackFunctions.set(key, callBack) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] addCallBackFunction -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function removeCallBackFunction(key, callBackFunction) { + function removeCallBackFunction (key, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] removeCallBackFunction -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] removeCallBackFunction -> Entering function."); } - - callBackFunctions.delete(key); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] removeCallBackFunction -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBackFunctions.delete(key) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] removeCallBackFunction -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function animationLoop() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] animationLoop -> Entering function."); } - - if (window.canvasApp.visible === true) { + function animationLoop () { + try { + if (INFO_LOG === true) { logger.write('[INFO] animationLoop -> Entering function.') } + if (window.canvasApp.visible === true) { /* We set the canvas to its normal width and height */ - browserCanvas.width = window.innerWidth; - browserCanvas.height = window.innerHeight - window.canvasApp.topMargin; + browserCanvas.width = window.innerWidth + browserCanvas.height = window.innerHeight - window.canvasApp.topMargin /* First thing is to clear the actual canvas */ - clearBrowserCanvas(); + clearBrowserCanvas() /* We loop through the callback functions collections and execute them all. */ - callBackFunctions.forEach(function (callBackFunction) { - - callBackFunction(); - - }); - - } else { - - browserCanvas.width = 1; - browserCanvas.height = 1; - - } + callBackFunctions.forEach(function (callBackFunction) { + callBackFunction() + }) + } else { + browserCanvas.width = 1 + browserCanvas.height = 1 + } /* We request the next frame to be drawn, and stablishing a loop */ - animationLoopHandle = window.requestAnimationFrame(animationLoop); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] animationLoop -> err = " + err); } - - } + animationLoopHandle = window.requestAnimationFrame(animationLoop) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] animationLoop -> err = ' + err) } } + } - function clearBrowserCanvas() { + function clearBrowserCanvas () { + if (INFO_LOG === true) { logger.write('[INFO] clearBrowserCanvas -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] clearBrowserCanvas -> Entering function."); } + browserCanvasContext.beginPath() - browserCanvasContext.beginPath(); + browserCanvasContext.rect(0, 0, browserCanvas.width, browserCanvas.height) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' - browserCanvasContext.rect(0, 0, browserCanvas.width, browserCanvas.height); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - - browserCanvasContext.closePath(); - browserCanvasContext.fill(); - - } + browserCanvasContext.closePath() + browserCanvasContext.fill() + } } - - - - - - diff --git a/BottomSpace/ChartAspectRatio.js b/BottomSpace/ChartAspectRatio.js index c448a872e..16b4ffe3d 100644 --- a/BottomSpace/ChartAspectRatio.js +++ b/BottomSpace/ChartAspectRatio.js @@ -1,130 +1,113 @@ -function newChartAspectRatio() { + function newChartAspectRatio () { + let thisObject = { + aspectRatio: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - aspectRatio: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 50 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 50; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize(); + container.isDraggeable = false + container.isClickeable = false + container.isWheeleable = true - container.isDraggeable = false; - container.isClickeable = false; - container.isWheeleable = true; + thisObject.aspectRatio = {} - thisObject.aspectRatio = {}; + const INITIAL_Y_ASPECT_RATIO = 5 / 10 + const MIN_Y_ASPECT_RATIO = 1 / 10 + const MAX_Y_ASPECT_RATIO = 10 / 10 - const INITIAL_Y_ASPECT_RATIO = 5 / 10; - const MIN_Y_ASPECT_RATIO = 1 / 10; - const MAX_Y_ASPECT_RATIO = 10 / 10; + thisObject.aspectRatio.x = 1 + thisObject.aspectRatio.y = INITIAL_Y_ASPECT_RATIO - thisObject.aspectRatio.x = 1; - thisObject.aspectRatio.y = INITIAL_Y_ASPECT_RATIO; + canDrawIcon = false - canDrawIcon = false; + return thisObject - return thisObject; + function initialize () { + icon = new Image() - function initialize() { + icon.onload = onImageLoad - icon = new Image(); + function onImageLoad () { + canDrawIcon = true + } - icon.onload = onImageLoad; + icon.src = window.canvasApp.urlPrefix + 'Images/Icons/chart-scale.png' - function onImageLoad() { - canDrawIcon = true; - } + thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel) - icon.src = window.canvasApp.urlPrefix + "Images/Icons/chart-scale.png"; + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } - thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel); + function resize () { + container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + function onMouseWheel (pDelta) { + if (viewPort.isMinZoom() === false) { return } // We only make this button to work at the min zoom level. - } + if (pDelta < 0) { + pDelta = -0.1 + } else { + pDelta = 0.1 + } - function resize() { + thisObject.aspectRatio.y = thisObject.aspectRatio.y + pDelta + thisObject.aspectRatio.y = Math.round(thisObject.aspectRatio.y * 100) / 100 - container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + if (thisObject.aspectRatio.y < MIN_Y_ASPECT_RATIO) { + thisObject.aspectRatio.y = MIN_Y_ASPECT_RATIO + } - } + if (thisObject.aspectRatio.y > MAX_Y_ASPECT_RATIO) { + thisObject.aspectRatio.y = MAX_Y_ASPECT_RATIO + } - function onMouseWheel(pDelta) { + thisObject.container.eventHandler.raiseEvent('Chart Aspect Ratio Changed', thisObject.aspectRatio) + } - if (viewPort.isMinZoom() === false) { return; } // We only make this button to work at the min zoom level. - - if (pDelta < 0) { - pDelta = -0.1; - } else { - pDelta = 0.1; - } - - thisObject.aspectRatio.y = thisObject.aspectRatio.y + pDelta; - thisObject.aspectRatio.y = Math.round(thisObject.aspectRatio.y * 100) / 100; - - if (thisObject.aspectRatio.y < MIN_Y_ASPECT_RATIO) { - - thisObject.aspectRatio.y = MIN_Y_ASPECT_RATIO; - - } - - if (thisObject.aspectRatio.y > MAX_Y_ASPECT_RATIO) { - - thisObject.aspectRatio.y = MAX_Y_ASPECT_RATIO; - - } - - thisObject.container.eventHandler.raiseEvent("Chart Aspect Ratio Changed", thisObject.aspectRatio); - - } - - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - } + return undefined + } + } - function draw() { + function draw () { + thisObject.container.frame.draw(false, false) - thisObject.container.frame.draw(false, false); + if (canDrawIcon === false) { return } + if (viewPort.isMinZoom() === false) { return } // We only show this button at the min zoom level. - if (canDrawIcon === false) { return; } - if (viewPort.isMinZoom() === false) { return; } // We only show this button at the min zoom level. + let breakpointsHeight = 15 - let breakpointsHeight = 15; + let imageHeight = 15 + let imageWidth = 15 - let imageHeight = 15; - let imageWidth = 15; + let imagePoint = { + x: 10, + y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight + } - let imagePoint = { - x: 10, - y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight - }; + imagePoint = thisObject.container.frame.frameThisPoint(imagePoint) - imagePoint = thisObject.container.frame.frameThisPoint(imagePoint); - - browserCanvasContext.drawImage(icon, imagePoint.x, imagePoint.y, imageWidth, imageHeight); - } - -} \ No newline at end of file + browserCanvasContext.drawImage(icon, imagePoint.x, imagePoint.y, imageWidth, imageHeight) + } + } diff --git a/BottomSpace/DeleteTradingHistory.js b/BottomSpace/DeleteTradingHistory.js index f57c08f1f..e6009bacd 100644 --- a/BottomSpace/DeleteTradingHistory.js +++ b/BottomSpace/DeleteTradingHistory.js @@ -1,86 +1,75 @@ - -function newDeleteTradingHistory() { +  +function newDeleteTradingHistory () { + const MODULE_NAME = 'Delete Trading History' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Delete Trading History"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + var thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container - var container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 50 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 50; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize(); + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + let icon + let canDrawIcon = false - let icon; - let canDrawIcon = false; + return thisObject - return thisObject; + function initialize (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } - function initialize(callBackFunction) { + icon = new Image() - try { + icon.onload = onImageLoad - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function onImageLoad () { + canDrawIcon = true + } - icon = new Image(); + icon.src = window.canvasApp.urlPrefix + 'Images/Icons/trash.png' - icon.onload = onImageLoad; + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - function onImageLoad() { - canDrawIcon = true; - } - - icon.src = window.canvasApp.urlPrefix + "Images/Icons/trash.png"; - - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); - - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } - } + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } } + } - function resize() { + function resize () { + container.frame.position.x = viewPort.visibleArea.topRight.x + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } - container.frame.position.x = viewPort.visibleArea.topRight.x; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + function onClick () { + try { + if (INFO_LOG === true) { logger.write('[INFO] onClick -> Entering function.') } - } + let sessionToken = window.localStorage.getItem('sessionToken') - - function onClick() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] onClick -> Entering function."); } - - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } + return + } /* @@ -94,243 +83,201 @@ function newDeleteTradingHistory() { 6. Delete every execution context file found. 7. Delete the execution history file after finishing the interation. 8. Delete the Sequence file belonging to the received Start Mode. - 9. Save the Status Report without the records of this Start Mode. - + 9. Save the Status Report without the records of this Start Mode. + */ - let storage = AzureStorage.Blob; + let storage = AzureStorage.Blob - let readOnlyBlobService; - let writeOnlyBlobService; - let deleteOnlyBlobService; + let readOnlyBlobService + let writeOnlyBlobService + let deleteOnlyBlobService - let readConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + "." + "READ"); + let readConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + '.' + 'READ') - if (readConnectionString !== undefined) { - readOnlyBlobService = storage.createBlobService(readConnectionString); - } + if (readConnectionString !== undefined) { + readOnlyBlobService = storage.createBlobService(readConnectionString) + } - let writeConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + "." + "WRITE"); + let writeConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + '.' + 'WRITE') - if (writeConnectionString !== undefined) { - writeOnlyBlobService = storage.createBlobService(writeConnectionString); - } + if (writeConnectionString !== undefined) { + writeOnlyBlobService = storage.createBlobService(writeConnectionString) + } - let deleteConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + "." + "DELETE"); + let deleteConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + '.' + 'DELETE') - if (deleteConnectionString !== undefined) { - deleteOnlyBlobService = storage.createBlobService(deleteConnectionString); - } + if (deleteConnectionString !== undefined) { + deleteOnlyBlobService = storage.createBlobService(deleteConnectionString) + } - let containerName = window.DEV_TEAM.toLowerCase(); + let containerName = window.DEV_TEAM.toLowerCase() - let statusReportFilePath = window.DEV_TEAM + "/" + window.CURRENT_BOT_CODE_NAME + ".1.0" + "/" + "AACloud.1.1" + "/" + "Poloniex" + "/" + "dataSet.V1" + "/" + "Reports" + "/" + "Trading-Process"; - let statusReportFileName = window.CURRENT_START_MODE + "." + "Status.Report.USDT_BTC.json"; + let statusReportFilePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Reports' + '/' + 'Trading-Process' + let statusReportFileName = window.CURRENT_START_MODE + '.' + 'Status.Report.USDT_BTC.json' - readOnlyBlobService.getBlobToText(containerName, statusReportFilePath + "/" + statusReportFileName, onStatusReport); + readOnlyBlobService.getBlobToText(containerName, statusReportFilePath + '/' + statusReportFileName, onStatusReport) - function onStatusReport(err, text, response) { + function onStatusReport (err, text, response) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onClick -> onStatusReport -> Entering function.') } - try { + if (err && err.code === 'BlobNotFound') { + console.log(statusReportFilePath + '/' + statusReportFileName + ' not found. No history detected for this start mode.') + return + } - if (INFO_LOG === true) { logger.write("[INFO] onClick -> onStatusReport -> Entering function."); } + let statusReport = JSON.parse(text) - if (err && err.code === 'BlobNotFound') { - - console.log(statusReportFilePath + "/" + statusReportFileName + " not found. No history detected for this start mode."); - return; - } - - let statusReport = JSON.parse(text); - - let toBeDeleted = 0; - let deleted = 0; - - for (let i = 0; i < statusReport.runs.length; i++) { + let toBeDeleted = 0 + let deleted = 0 + for (let i = 0; i < statusReport.runs.length; i++) { /* For each record, we will get the execution history file. */ - let filePath = window.DEV_TEAM + "/" + window.CURRENT_BOT_CODE_NAME + ".1.0" + "/" + "AACloud.1.1" + "/" + "Poloniex" + "/" + "dataSet.V1" + "/" + "Output" + "/" + "Trading-Process"; - let fileName = "Execution.History." + window.CURRENT_START_MODE + "." + i + ".json"; + let filePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Output' + '/' + 'Trading-Process' + let fileName = 'Execution.History.' + window.CURRENT_START_MODE + '.' + i + '.json' - readOnlyBlobService.getBlobToText(containerName, filePath + "/" + fileName, onExecutionHistory); + readOnlyBlobService.getBlobToText(containerName, filePath + '/' + fileName, onExecutionHistory) - function onExecutionHistory(err, text, response) { + function onExecutionHistory (err, text, response) { + let executionHistory = JSON.parse(text) - let executionHistory = JSON.parse(text); + for (let j = 0; j < executionHistory.length; j++) { + let dateTime = new Date(executionHistory[j][0]) - for (let j = 0; j < executionHistory.length; j++) { + let datePath = dateTime.getUTCFullYear() + '/' + pad(dateTime.getUTCMonth() + 1, 2) + '/' + pad(dateTime.getUTCDate(), 2) + '/' + pad(dateTime.getUTCHours(), 2) + '/' + pad(dateTime.getUTCMinutes(), 2) - let dateTime = new Date(executionHistory[j][0]); + let filePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Output' + '/' + 'Trading-Process' + '/' + datePath + let fileName = 'Execution.Context.' + window.CURRENT_START_MODE + '.' + i + '.json' - let datePath = dateTime.getUTCFullYear() + "/" + pad(dateTime.getUTCMonth() + 1, 2) + "/" + pad(dateTime.getUTCDate(), 2) + "/" + pad(dateTime.getUTCHours(), 2) + "/" + pad(dateTime.getUTCMinutes(), 2); + deleteOnlyBlobService.deleteBlob(containerName, filePath + '/' + fileName, onDeleted) - let filePath = window.DEV_TEAM + "/" + window.CURRENT_BOT_CODE_NAME + ".1.0" + "/" + "AACloud.1.1" + "/" + "Poloniex" + "/" + "dataSet.V1" + "/" + "Output" + "/" + "Trading-Process" + "/" + datePath; - let fileName = "Execution.Context." + window.CURRENT_START_MODE + "." + i + ".json"; + toBeDeleted++ - deleteOnlyBlobService.deleteBlob(containerName, filePath + "/" + fileName, onDeleted); + function onDeleted (err, text, response) { + if (err) { - toBeDeleted++; + console.log(filePath + '/' + fileName + ' NOT deleted.') + console.log('err.message = ' + err.message) + } else { - function onDeleted(err, text, response) { + console.log(filePath + '/' + fileName + ' deleted.') + } - if (err) { + deleted++ - console.log(filePath + "/" + fileName + " NOT deleted."); - console.log("err.message = " + err.message); - } else { + if (toBeDeleted === deleted) { - console.log(filePath + "/" + fileName + " deleted."); - - } - - deleted++; - - if (toBeDeleted === deleted) { - - updateStatusReport(); - - } - } - } + updateStatusReport() + } + } + } /* Now we delete the execution history file. */ - deleteOnlyBlobService.deleteBlob(containerName, filePath + "/" + fileName, onExecutionHistoryDeleted); + deleteOnlyBlobService.deleteBlob(containerName, filePath + '/' + fileName, onExecutionHistoryDeleted) - function onExecutionHistoryDeleted(err, text, response) { + function onExecutionHistoryDeleted (err, text, response) { + console.log(filePath + '/' + fileName + ' deleted.') + } + } + } - console.log(filePath + "/" + fileName + " deleted."); + function updateStatusReport () { + try { + if (INFO_LOG === true) { logger.write('[INFO] onClick -> onStatusReport -> updateStatusReport -> Entering function.') } - } - } - } - - function updateStatusReport() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] onClick -> onStatusReport -> updateStatusReport -> Entering function."); } - - statusReport.runs = []; + statusReport.runs = [] /* Here is where we update the current Status Report file with the new version without records for the current Start Mode. */ - let fileContent = JSON.stringify(statusReport); + let fileContent = JSON.stringify(statusReport) - writeOnlyBlobService.createBlockBlobFromText(containerName, statusReportFilePath + "/" + statusReportFileName, fileContent, onStatusReportUpdated); + writeOnlyBlobService.createBlockBlobFromText(containerName, statusReportFilePath + '/' + statusReportFileName, fileContent, onStatusReportUpdated) - function onStatusReportUpdated(err, text, response) { - - console.log(statusReportFilePath + "/" + statusReportFileName + " updated."); - - } + function onStatusReportUpdated (err, text, response) { + console.log(statusReportFilePath + '/' + statusReportFileName + ' updated.') + } /* Finally we delete the sequence file. */ - let filePath = window.DEV_TEAM + "/" + window.CURRENT_BOT_CODE_NAME + ".1.0" + "/" + "AACloud.1.1" + "/" + "Poloniex" + "/" + "dataSet.V1" + "/" + "Output" + "/" + "Trading-Process"; - let fileName = "Execution.History." + window.CURRENT_START_MODE + "." + "Sequence" + ".json"; + let filePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Output' + '/' + 'Trading-Process' + let fileName = 'Execution.History.' + window.CURRENT_START_MODE + '.' + 'Sequence' + '.json' - deleteOnlyBlobService.deleteBlob(containerName, filePath + "/" + fileName, onDeleted); + deleteOnlyBlobService.deleteBlob(containerName, filePath + '/' + fileName, onDeleted) - function onDeleted(err, text, response) { - - console.log(filePath + "/" + fileName + " deleted."); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onClick -> onStatusReport -> updateStatusReport -> err.message = " + err.message); } - - } - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onClick -> onStatusReport -> err.message = " + err.message); } - - } + function onDeleted (err, text, response) { + console.log(filePath + '/' + fileName + ' deleted.') + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onClick -> onStatusReport -> updateStatusReport -> err.message = ' + err.message) } } - - function pad(str, max) { - str = str.toString(); - return str.length < max ? pad("0" + str, max) : str; - } - - + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onClick -> err.message = " + err.message); } - + if (ERROR_LOG === true) { logger.write('[ERROR] onClick -> onStatusReport -> err.message = ' + err.message) } } + } + + function pad (str, max) { + str = str.toString() + return str.length < max ? pad('0' + str, max) : str + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onClick -> err.message = ' + err.message) } } + } - function getContainer(point) { + function getContainer (point) { + try { + if (INFO_LOG === true) { logger.write('[INFO] getContainer -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] getContainer -> Entering function."); } - - let container; + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getContainer -> err.message = " + err.message); } - - } + return undefined + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getContainer -> err.message = ' + err.message) } } + } - function draw() { + function draw () { + try { + if (INFO_LOG === true) { logger.write('[INFO] draw -> Entering function.') } - try { + let sessionToken = window.localStorage.getItem('sessionToken') - if (INFO_LOG === true) { logger.write("[INFO] draw -> Entering function."); } - - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } + return + } - thisObject.container.frame.draw(false, false); + thisObject.container.frame.draw(false, false) - if (canDrawIcon === false) { return; } + if (canDrawIcon === false) { return } - let breakpointsHeight = 14; + let breakpointsHeight = 14 - let imageHeight = 15; - let imageWidth = 15; + let imageHeight = 15 + let imageWidth = 15 - let imagePoint = { - x: 10, - y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight - }; + let imagePoint = { + x: 10, + y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight + } - imagePoint = thisObject.container.frame.frameThisPoint(imagePoint); + imagePoint = thisObject.container.frame.frameThisPoint(imagePoint) - browserCanvasContext.drawImage(icon, imagePoint.x, imagePoint.y, imageWidth, imageHeight); - - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] draw -> err.message = " + err.message); } - - } + browserCanvasContext.drawImage(icon, imagePoint.x, imagePoint.y, imageWidth, imageHeight) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] draw -> err.message = ' + err.message) } } -} \ No newline at end of file + } +} diff --git a/BottomSpace/PlayStopButton.js b/BottomSpace/PlayStopButton.js index 693e3e66a..a287ac6d7 100644 --- a/BottomSpace/PlayStopButton.js +++ b/BottomSpace/PlayStopButton.js @@ -1,164 +1,148 @@ - -function newPlayStopButton() { +  +function newPlayStopButton () { + var thisObject = { + container: undefined, + setDatetime: setDatetime, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - setDatetime: setDatetime, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container - var container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 50 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 50; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize(); + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + let play + let stop + let canDraw = false + let showing = 'Play' + let image - let play; - let stop; - let canDraw = false; - let showing = "Play"; - let image; + let datetime + let timePeriod - let datetime; - let timePeriod; + return thisObject - return thisObject; + function initialize () { + play = new Image() - function initialize() { - - play = new Image(); - - play.onload = onImageLoad; - - function onImageLoad() { - image = play; - canDraw = true; - } - - play.src = window.canvasApp.urlPrefix + "Images/Icons/play.png"; - - stop = new Image(); - - stop.src = window.canvasApp.urlPrefix + "Images/Icons/pause.png"; - - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - - viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged); - timePeriod = INITIAL_TIME_PERIOD; - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + play.onload = onImageLoad + function onImageLoad () { + image = play + canDraw = true } - function resize() { + play.src = window.canvasApp.urlPrefix + 'Images/Icons/play.png' - container.frame.position.x = viewPort.visibleArea.topLeft.x + 150 * 4; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + stop = new Image() - } + stop.src = window.canvasApp.urlPrefix + 'Images/Icons/pause.png' + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - function onClick() { + viewPort.eventHandler.listenToEvent('Zoom Changed', onZoomChanged) + timePeriod = INITIAL_TIME_PERIOD - let sessionToken = window.localStorage.getItem('sessionToken'); + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } - if (sessionToken === null || sessionToken === "") { + function resize () { + container.frame.position.x = viewPort.visibleArea.topLeft.x + 150 * 4 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } + + function onClick () { + let sessionToken = window.localStorage.getItem('sessionToken') + + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; + return + } + + switch (showing) { + + case 'Play': { + image = stop + showing = 'Stop' + + let UI_COMMANDS = { + beginDatetime: datetime, + endDatetime: undefined, + timePeriod: timePeriod, + startMode: window.CURRENT_START_MODE, + eventHandler: thisObject.container.eventHandler } - switch (showing) { + cloudVM.onBotPlayPressed(UI_COMMANDS) - case "Play": { - image = stop; - showing = "Stop"; + break + } + case 'Stop': { + image = play + showing = 'Play' - let UI_COMMANDS = { - beginDatetime: datetime, - endDatetime: undefined, - timePeriod: timePeriod, - startMode: window.CURRENT_START_MODE, - eventHandler: thisObject.container.eventHandler - }; + cloudVM.onBotStopPressed() - cloudVM.onBotPlayPressed(UI_COMMANDS); - - break; - } - case "Stop": { - image = play; - showing = "Play"; - - cloudVM.onBotStopPressed(); - - break; - } - } + break + } } + } - function onZoomChanged(event) { + function onZoomChanged (event) { + timePeriod = recalculatePeriod(event.newLevel) + } - timePeriod = recalculatePeriod(event.newLevel); + function setDatetime (pDatetime) { + datetime = new Date(pDatetime) + } - } - - function setDatetime(pDatetime) { - - datetime = new Date(pDatetime); - } - - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } + } - function draw() { + function draw () { + let sessionToken = window.localStorage.getItem('sessionToken') - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - thisObject.container.frame.draw(false, false); - - let breakpointsHeight = 14; - - if (canDraw === false) { return; } - - let imageHeight = 20; - let imageWidth = 20; - - let imagePoint = { - x: thisObject.container.frame.width / 2 - imageWidth / 2, - y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight - }; - - imagePoint = thisObject.container.frame.frameThisPoint(imagePoint); - - browserCanvasContext.drawImage(image, imagePoint.x, imagePoint.y, imageWidth, imageHeight); + return } -} \ No newline at end of file + + thisObject.container.frame.draw(false, false) + + let breakpointsHeight = 14 + + if (canDraw === false) { return } + + let imageHeight = 20 + let imageWidth = 20 + + let imagePoint = { + x: thisObject.container.frame.width / 2 - imageWidth / 2, + y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight + } + + imagePoint = thisObject.container.frame.frameThisPoint(imagePoint) + + browserCanvasContext.drawImage(image, imagePoint.x, imagePoint.y, imageWidth, imageHeight) + } +} diff --git a/BreakpointsBar.js b/BreakpointsBar.js index 749b9d7b0..a13023e08 100644 --- a/BreakpointsBar.js +++ b/BreakpointsBar.js @@ -1,219 +1,195 @@ - -function newBreakpointsBar() { - var thisObject = { - setDatetime: setDatetime, - container: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; +function newBreakpointsBar () { + var thisObject = { + setDatetime: setDatetime, + container: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var container = newContainer(); - container.initialize(); - thisObject.container = container; + var container = newContainer() + container.initialize() + thisObject.container = container - thisObject.container.frame.width = browserCanvasContext.width; - thisObject.container.frame.height = 15; + thisObject.container.frame.width = browserCanvasContext.width + thisObject.container.frame.height = 15 - container.frame.position.x = 0; - container.frame.position.y = viewPort.visibleArea.bottomRight.y; + container.frame.position.x = 0 + container.frame.position.y = viewPort.visibleArea.bottomRight.y - container.isDraggeable = false; - container.isClickeable = true; + container.isDraggeable = false + container.isClickeable = true - let logo; - let canDrawLogo = false; + let logo + let canDrawLogo = false - let datetime; - let timePeriod; - let timeLineCoordinateSystem; - let chartContainer; + let datetime + let timePeriod + let timeLineCoordinateSystem + let chartContainer - let breakpointsByTimePeriod = new Map(); + let breakpointsByTimePeriod = new Map() - return thisObject; + return thisObject - function initialize(pChartContainer, pTimeLineCoordinateSystem) { + function initialize (pChartContainer, pTimeLineCoordinateSystem) { + timeLineCoordinateSystem = pTimeLineCoordinateSystem + chartContainer = pChartContainer - timeLineCoordinateSystem = pTimeLineCoordinateSystem; - chartContainer = pChartContainer; + viewPort.eventHandler.listenToEvent('Zoom Changed', onZoomChanged) + timePeriod = INITIAL_TIME_PERIOD - viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged); - timePeriod = INITIAL_TIME_PERIOD; + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - - for (let i = 0; i < marketFilesPeriods.length; i++) { - - let breakpointsMap = new Map(); - breakpointsByTimePeriod.set(marketFilesPeriods[i][0], breakpointsMap); - - } - - for (let i = 0; i < dailyFilePeriods.length; i++) { - - let breakpointsMap = new Map(); - breakpointsByTimePeriod.set(dailyFilePeriods[i][0], breakpointsMap); - - } + for (let i = 0; i < marketFilesPeriods.length; i++) { + let breakpointsMap = new Map() + breakpointsByTimePeriod.set(marketFilesPeriods[i][0], breakpointsMap) } - function onClick(pPoint) { + for (let i = 0; i < dailyFilePeriods.length; i++) { + let breakpointsMap = new Map() + breakpointsByTimePeriod.set(dailyFilePeriods[i][0], breakpointsMap) + } + } - let point = { - x: pPoint.x, - y: pPoint.y - }; + function onClick (pPoint) { + let point = { + x: pPoint.x, + y: pPoint.y + } - let miliSeconds = getMilisecondsFromPoint(point, chartContainer, timeLineCoordinateSystem); + let miliSeconds = getMilisecondsFromPoint(point, chartContainer, timeLineCoordinateSystem) - miliSeconds = normalizeX(miliSeconds); // We are now exactly at the middle of the "candle" correspondind to the point clicked. + miliSeconds = normalizeX(miliSeconds) // We are now exactly at the middle of the "candle" correspondind to the point clicked. - let breakpointsMap = breakpointsByTimePeriod.get(timePeriod); - let breakpoint = breakpointsMap.get(miliSeconds); - - if (breakpoint === undefined) { + let breakpointsMap = breakpointsByTimePeriod.get(timePeriod) + let breakpoint = breakpointsMap.get(miliSeconds) + if (breakpoint === undefined) { /* The breakpoint didnt exist, then we create one. */ - breakpointsMap.set(miliSeconds, 1); - - } else { - + breakpointsMap.set(miliSeconds, 1) + } else { /* The breakpoint existed, so we remove it. */ - breakpointsMap.set(miliSeconds, undefined); - - } + breakpointsMap.set(miliSeconds, undefined) } + } - function normalizeX(pX) { + function normalizeX (pX) { + return Math.trunc(pX / timePeriod) * timePeriod + timePeriod / 2 + } - return Math.trunc(pX / timePeriod) * timePeriod + timePeriod / 2; + function onZoomChanged (event) { + timePeriod = recalculatePeriod(event.newLevel) + } - } + function setDatetime (pDatetime) { + datetime = new Date(pDatetime) + } - function onZoomChanged(event) { - - timePeriod = recalculatePeriod(event.newLevel); - - } - - function setDatetime(pDatetime) { - - datetime = new Date(pDatetime); - } - - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } + } - function draw() { - + function draw () { /* To draw the breakpoints, we will calculate the miliseconds for the first x pixel of the breakpoint bar, and for the last x pixel. Once we have that we can create an array with all the possible points for breack points. Finally we can see if brealpoints exists at those points. We plot only the ones that exists. */ - let breakpointsMap = breakpointsByTimePeriod.get(timePeriod); + let breakpointsMap = breakpointsByTimePeriod.get(timePeriod) - let beginX = { - x: viewPort.visibleArea.bottomLeft.x, - y: 0 - }; + let beginX = { + x: viewPort.visibleArea.bottomLeft.x, + y: 0 + } - let endX = { - x: viewPort.visibleArea.bottomRight.x, - y: 0 - }; + let endX = { + x: viewPort.visibleArea.bottomRight.x, + y: 0 + } - let beginMiliseconds = getMilisecondsFromPoint(beginX, chartContainer, timeLineCoordinateSystem); - let endMiliseconds = getMilisecondsFromPoint(endX, chartContainer, timeLineCoordinateSystem); + let beginMiliseconds = getMilisecondsFromPoint(beginX, chartContainer, timeLineCoordinateSystem) + let endMiliseconds = getMilisecondsFromPoint(endX, chartContainer, timeLineCoordinateSystem) - beginMiliseconds = normalizeX(beginMiliseconds); - endMiliseconds = normalizeX(endMiliseconds); + beginMiliseconds = normalizeX(beginMiliseconds) + endMiliseconds = normalizeX(endMiliseconds) - window.AT_BREAKPOINT = false; + window.AT_BREAKPOINT = false - for (let miliSeconds = beginMiliseconds; miliSeconds < endMiliseconds; miliSeconds = miliSeconds + timePeriod) { + for (let miliSeconds = beginMiliseconds; miliSeconds < endMiliseconds; miliSeconds = miliSeconds + timePeriod) { + let breakpoint = breakpointsMap.get(miliSeconds) - let breakpoint = breakpointsMap.get(miliSeconds); + if (breakpoint !== undefined) { + let point1 = { + x: miliSeconds, + y: 0 + } - if (breakpoint !== undefined) { + point1 = timeLineCoordinateSystem.transformThisPoint(point1) + point1 = transformThisPoint(point1, chartContainer) - let point1 = { - x: miliSeconds, - y: 0 - } + let point2 = { + x: miliSeconds, + y: thisObject.container.frame.height / 2 + 1 + } - point1 = timeLineCoordinateSystem.transformThisPoint(point1); - point1 = transformThisPoint(point1, chartContainer); + point2 = thisObject.container.frame.frameThisPoint(point2) - let point2 = { - x: miliSeconds, - y: thisObject.container.frame.height / 2 + 1 - } + let point = { + x: point1.x, + y: point2.y + } - point2 = thisObject.container.frame.frameThisPoint(point2); + let isCurrentRecord = false - let point = { - x: point1.x, - y: point2.y - } + if (datetime !== undefined) { + let dateValue = datetime.valueOf() + if (dateValue >= miliSeconds - timePeriod / 2 && dateValue <= miliSeconds + timePeriod / 2 - 1) { + isCurrentRecord = true + } + } - let isCurrentRecord = false; + let radius = 5 - if (datetime !== undefined) { - let dateValue = datetime.valueOf(); - if (dateValue >= miliSeconds - timePeriod / 2 && dateValue <= miliSeconds + timePeriod / 2 - 1) { - isCurrentRecord = true; - } - } + let opacity = '0.5' - let radius = 5; - - let opacity = '0.5'; - - browserCanvasContext.lineWidth = 1; + browserCanvasContext.lineWidth = 1 /* Outer Circle */ - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - browserCanvasContext.strokeStyle = 'rgba(123, 50, 40, ' + opacity + ')'; + browserCanvasContext.strokeStyle = 'rgba(123, 50, 40, ' + opacity + ')' - if (isCurrentRecord === false) { - browserCanvasContext.fillStyle = 'rgba(223, 70, 60, ' + opacity + ')'; - } else { - browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + opacity + ')'; /* highlight the current record */ + if (isCurrentRecord === false) { + browserCanvasContext.fillStyle = 'rgba(223, 70, 60, ' + opacity + ')' + } else { + browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + opacity + ')' /* highlight the current record */ - window.AT_BREAKPOINT = true; // We are hitting a breakpoint! - } - - browserCanvasContext.arc(point.x, point.y, radius, 0, Math.PI * 2, true); - browserCanvasContext.closePath(); - - if (point.x < viewPort.visibleArea.topLeft.x + 50 || point.x > viewPort.visibleArea.bottomRight.x - 50) {/*we leave this history without fill. */ } else { - browserCanvasContext.fill(); - } - - browserCanvasContext.stroke(); - } + window.AT_BREAKPOINT = true // We are hitting a breakpoint! } + + browserCanvasContext.arc(point.x, point.y, radius, 0, Math.PI * 2, true) + browserCanvasContext.closePath() + + if (point.x < viewPort.visibleArea.topLeft.x + 50 || point.x > viewPort.visibleArea.bottomRight.x - 50) { /* we leave this history without fill. */ } else { + browserCanvasContext.fill() + } + + browserCanvasContext.stroke() + } } -} \ No newline at end of file + } +} diff --git a/Candle.js b/Candle.js index 40f14ea15..19c847b3a 100644 --- a/Candle.js +++ b/Candle.js @@ -1,17 +1,15 @@ -function newCandle() { +function newCandle () { + var candle = { + open: undefined, + close: undefined, + min: 10000000000000, + max: 0, + begin: undefined, + end: undefined, + direction: undefined, + beginId: undefined, + endId: undefined + } - var candle = { - open: undefined, - close: undefined, - min: 10000000000000, - max: 0, - begin: undefined, - end: undefined, - direction: undefined, - beginId: undefined, - endId: undefined - }; - - return candle; - -} \ No newline at end of file + return candle +} diff --git a/Canvas.js b/Canvas.js index 02b34f933..cf104b1aa 100644 --- a/Canvas.js +++ b/Canvas.js @@ -1,52 +1,51 @@ - -let browserCanvasContext; // The context of the canvas object. +  +let browserCanvasContext // The context of the canvas object. -let stepsInitializationCounter = 0; // This counter the initialization steps required to be able to turn off the splash screen. -let marketInitializationCounter = 0; // This counter the initialization of markets required to be able to turn off the splash screen. -let splashScreenNeeded = true; +let stepsInitializationCounter = 0 // This counter the initialization steps required to be able to turn off the splash screen. +let marketInitializationCounter = 0 // This counter the initialization of markets required to be able to turn off the splash screen. +let splashScreenNeeded = true -function newCanvas() { - - const MODULE_NAME = "Canvas"; - const INFO_LOG = false; - const ERROR_LOG = true; - const INTENSIVE_LOG = false; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; +function newCanvas () { + const MODULE_NAME = 'Canvas' + const INFO_LOG = false + const ERROR_LOG = true + const INTENSIVE_LOG = false + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME /* Mouse event related variables. */ - let containerDragStarted = false; - let floatingObjectDragStarted = false; - let floatingObjectBeingDragged; - let containerBeingDragged; - let viewPortBeingDragged = false; + let containerDragStarted = false + let floatingObjectDragStarted = false + let floatingObjectBeingDragged + let containerBeingDragged + let viewPortBeingDragged = false - let dragVector = { - downX: 0, - downY: 0, - upX: 0, - upY: 0 - }; + let dragVector = { + downX: 0, + downY: 0, + upX: 0, + upY: 0 + } /* canvas object */ - let thisObject = { - eventHandler: undefined, - topSpace: undefined, - chartSpace: undefined, - floatingSpace: undefined, - panelsSpace: undefined, - bottomSpace: undefined, - animation: undefined, - initialize: initialize - }; + let thisObject = { + eventHandler: undefined, + topSpace: undefined, + chartSpace: undefined, + floatingSpace: undefined, + panelsSpace: undefined, + bottomSpace: undefined, + animation: undefined, + initialize: initialize + } - thisObject.eventHandler = newEventHandler(); + thisObject.eventHandler = newEventHandler() - let splashScreen; + let splashScreen - return thisObject; + return thisObject /* The canvas object represents a layer on top of the browser canvas object. @@ -55,7 +54,7 @@ function newCanvas() { 1. The "Top Space": It is where Team and User information is displayed. 2. The "Chart Space": It is where the charts are plotted. - 3. The "Floating Space": It is where floating elements live. There is a physics engine for this layer that allows these elements to flow. + 3. The "Floating Space": It is where floating elements live. There is a physics engine for this layer that allows these elements to flow. 4. The "Panels Space": It is where panels live. --> This space has yet to be develop, currently pannels are somehow at the Chart Space. 5. The "Bottom Space": Includes the breakpoint bar and a toolbar. @@ -79,663 +78,554 @@ function newCanvas() { ---> bottomSpace */ - function initialize(callBackFunction) { + function initialize (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } - try { + initializeBrowserCanvas() - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - - initializeBrowserCanvas(); - - addCanvasEvents(); + addCanvasEvents() /* Instantiate all the children spaces of Canvas object */ - thisObject.topSpace = newTopSpace(); - thisObject.topSpace.initialize(); + thisObject.topSpace = newTopSpace() + thisObject.topSpace.initialize() - thisObject.bottomSpace = newBottomSpace(); - thisObject.bottomSpace.initialize(); + thisObject.bottomSpace = newBottomSpace() + thisObject.bottomSpace.initialize() - thisObject.panelsSpace = newPanelsSpace(); - thisObject.panelsSpace.initialize(); + thisObject.panelsSpace = newPanelsSpace() + thisObject.panelsSpace.initialize() - thisObject.floatingSpace = newFloatingSpace(); - thisObject.floatingSpace.initialize(); + thisObject.floatingSpace = newFloatingSpace() + thisObject.floatingSpace.initialize() - thisObject.chartSpace = newChartSpace(); - thisObject.chartSpace.initialize(onCharSpaceInitialized); + thisObject.chartSpace = newChartSpace() + thisObject.chartSpace.initialize(onCharSpaceInitialized) - function onCharSpaceInitialized(err) { + function onCharSpaceInitialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCharSpaceInitialized -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCharSpaceInitialized -> Entering function."); } - - viewPort.raiseEvents(); // These events will impacts on objects just initialized. - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onCharSpaceInitialized -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } + viewPort.raiseEvents() // These events will impacts on objects just initialized. + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onCharSpaceInitialized -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } /* Splash Screen */ - splashScreen = newSplashScreen(); - splashScreen.initialize(); + splashScreen = newSplashScreen() + splashScreen.initialize() - let animation = newAnimation(); - animation.initialize(onAnimationInitialized); + let animation = newAnimation() + animation.initialize(onAnimationInitialized) - function onAnimationInitialized(err) { + function onAnimationInitialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onAnimationInitialized -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onAnimationInitialized -> Entering function."); } - - thisObject.animation = animation; + thisObject.animation = animation /* Here we add all the functions that will be called during the animation cycle. */ - animation.addCallBackFunction("Chart Space", thisObject.chartSpace.draw, onFunctionAdded); - animation.addCallBackFunction("Floating Space", thisObject.floatingSpace.floatingLayer.physicsLoop, onFunctionAdded); - animation.addCallBackFunction("Panels Space", thisObject.panelsSpace.draw, onFunctionAdded); - animation.addCallBackFunction("Splash Screen", splashScreen.draw, onFunctionAdded); - animation.addCallBackFunction("ViewPort Animate", viewPort.animate, onFunctionAdded); - animation.addCallBackFunction("ViewPort Draw", viewPort.draw, onFunctionAdded); - animation.addCallBackFunction("Bottom Space", thisObject.bottomSpace.draw, onFunctionAdded); - animation.addCallBackFunction("Top Space", thisObject.topSpace.draw, onFunctionAdded); - animation.start(onStart); + animation.addCallBackFunction('Chart Space', thisObject.chartSpace.draw, onFunctionAdded) + animation.addCallBackFunction('Floating Space', thisObject.floatingSpace.floatingLayer.physicsLoop, onFunctionAdded) + animation.addCallBackFunction('Panels Space', thisObject.panelsSpace.draw, onFunctionAdded) + animation.addCallBackFunction('Splash Screen', splashScreen.draw, onFunctionAdded) + animation.addCallBackFunction('ViewPort Animate', viewPort.animate, onFunctionAdded) + animation.addCallBackFunction('ViewPort Draw', viewPort.draw, onFunctionAdded) + animation.addCallBackFunction('Bottom Space', thisObject.bottomSpace.draw, onFunctionAdded) + animation.addCallBackFunction('Top Space', thisObject.topSpace.draw, onFunctionAdded) + animation.start(onStart) - function onFunctionAdded(err) { + function onFunctionAdded (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onAnimationInitialized -> onFunctionAdded -> Entering function.') } - try { + if (err.result === GLOBAL.DEFAULT_FAIL_RESPONSE.result) { + animation.stop() - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onAnimationInitialized -> onFunctionAdded -> Entering function."); } - - if (err.result === GLOBAL.DEFAULT_FAIL_RESPONSE.result) { - - animation.stop(); - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onAnimationInitialized -> onFunctionAdded -> Animation Stopped since a vital funtion could not be added."); } + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onAnimationInitialized -> onFunctionAdded -> Animation Stopped since a vital funtion could not be added.') } /* Display some Error Page here. */ - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onAnimationInitialized -> onFunctionAdded -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function onStart(err) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onAnimationInitialized -> onStart -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onAnimationInitialized -> onStart -> Received OK Response."); } - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - return; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onAnimationInitialized -> onStart -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onAnimationInitialized -> onStart -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onAnimationInitialized -> onStart -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onAnimationInitialized -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onAnimationInitialized -> onFunctionAdded -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + function onStart (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onAnimationInitialized -> onStart -> Entering function.') } + + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onAnimationInitialized -> onStart -> Received OK Response.') } + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + return + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onAnimationInitialized -> onStart -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onAnimationInitialized -> onStart -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onAnimationInitialized -> onStart -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onAnimationInitialized -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function initializeBrowserCanvas() { + function initializeBrowserCanvas () { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeBrowserCanvas -> Entering function.') } - try { + browserCanvasContext = browserCanvas.getContext('2d') - if (INFO_LOG === true) { logger.write("[INFO] initializeBrowserCanvas -> Entering function."); } - - browserCanvasContext = browserCanvas.getContext('2d'); - - viewPort.initialize(); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeBrowserCanvas -> err = " + err); } - - } + viewPort.initialize() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initializeBrowserCanvas -> err = ' + err) } } + } - function addCanvasEvents() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] addCanvasEvents -> Entering function."); } + function addCanvasEvents () { + try { + if (INFO_LOG === true) { logger.write('[INFO] addCanvasEvents -> Entering function.') } /* Mouse down and up events to control the drag of the canvas. */ - browserCanvas.addEventListener('mousedown', onMouseDown, false); - browserCanvas.addEventListener('mouseup', onMouseUp, false); - browserCanvas.addEventListener('mousemove', onMouseMove, false); - browserCanvas.addEventListener('click', onMouseClick, false); + browserCanvas.addEventListener('mousedown', onMouseDown, false) + browserCanvas.addEventListener('mouseup', onMouseUp, false) + browserCanvas.addEventListener('mousemove', onMouseMove, false) + browserCanvas.addEventListener('click', onMouseClick, false) /* Mouse wheel events. */ - if (browserCanvas.addEventListener) { + if (browserCanvas.addEventListener) { // IE9, Chrome, Safari, Opera - browserCanvas.addEventListener("mousewheel", onMouseWheel, false); + browserCanvas.addEventListener('mousewheel', onMouseWheel, false) // Firefox - browserCanvas.addEventListener("DOMMouseScroll", onMouseWheel, false); - } + browserCanvas.addEventListener('DOMMouseScroll', onMouseWheel, false) + } // IE 6/7/8 - else browserCanvas.attachEvent("onmousewheel", onMouseWheel); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] addCanvasEvents -> err = " + err); } - } + else browserCanvas.attachEvent('onmousewheel', onMouseWheel) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] addCanvasEvents -> err = ' + err) } } + } - function onMouseDown(event) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] onMouseDown -> Entering function."); } + function onMouseDown (event) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onMouseDown -> Entering function.') } /* - + There are four types of elements that can be dragged. - + 1. Panels. 2. Floating Elements (Currently only FloatingObjects). 3. Charts. 4. The Viewport. - + We eveluate each space in order to see if they are holding the element being dragged, and we fallout at the Viewport. - + */ - let point = { - x: event.pageX, - y: event.pageY - window.canvasApp.topMargin - }; + let point = { + x: event.pageX, + y: event.pageY - window.canvasApp.topMargin + } - dragVector.downX = point.x; - dragVector.downY = point.y; + dragVector.downX = point.x + dragVector.downY = point.y - let container; + let container /* We check if the mouse is over an element of the Top Space / */ - container = thisObject.topSpace.getContainer(point); + container = thisObject.topSpace.getContainer(point) - if (container !== undefined && container.isDraggeable === true) { - - containerBeingDragged = container; - containerDragStarted = true; - return; - } + if (container !== undefined && container.isDraggeable === true) { + containerBeingDragged = container + containerDragStarted = true + return + } /* We check if the mouse is over an element of the Bottom Space / */ - container = thisObject.bottomSpace.getContainer(point); + container = thisObject.bottomSpace.getContainer(point) - if (container !== undefined && container.isDraggeable === true) { - - containerBeingDragged = container; - containerDragStarted = true; - return; - } + if (container !== undefined && container.isDraggeable === true) { + containerBeingDragged = container + containerDragStarted = true + return + } /* We check if the mouse is over a panel/ */ - container = thisObject.panelsSpace.getContainer(point); + container = thisObject.panelsSpace.getContainer(point) - if (container !== undefined && container.isDraggeable === true) { - - containerBeingDragged = container; - containerDragStarted = true; - return; - } + if (container !== undefined && container.isDraggeable === true) { + containerBeingDragged = container + containerDragStarted = true + return + } /* We check if the mouse is over a floatingObject/ */ - floatingObjectBeingDragged = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y); + floatingObjectBeingDragged = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y) - if (floatingObjectBeingDragged >= 0) { - floatingObjectDragStarted = true; - return; - } + if (floatingObjectBeingDragged >= 0) { + floatingObjectDragStarted = true + return + } /* If it is not, then we check if it is over any of the existing containers at the Chart Space. */ - container = thisObject.chartSpace.getContainer(point); + container = thisObject.chartSpace.getContainer(point) - if (container !== undefined && container.isDraggeable === true) { + if (container !== undefined && container.isDraggeable === true) { + containerBeingDragged = container + containerDragStarted = true + return + } - containerBeingDragged = container; - containerDragStarted = true; - return; - } - - viewPortBeingDragged = true; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onMouseDown -> err = " + err); } - - } + viewPortBeingDragged = true + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onMouseDown -> err = ' + err) } } + } - function onMouseClick(event) { + function onMouseClick (event) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onMouseClick -> Entering function.') } - try { + let point = { + x: event.pageX, + y: event.pageY - window.canvasApp.topMargin + } - if (INFO_LOG === true) { logger.write("[INFO] onMouseClick -> Entering function."); } - - let point = { - x: event.pageX, - y: event.pageY - window.canvasApp.topMargin - }; - - let container; + let container /* We check if the mouse is over an element of the Top Space / */ - container = thisObject.topSpace.getContainer(point); + container = thisObject.topSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseClick', point); - return; - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseClick', point) + return + } /* We check if the mouse is over an element of the Bottom Space / */ - container = thisObject.bottomSpace.getContainer(point); + container = thisObject.bottomSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseClick', point); - return; - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseClick', point) + return + } /* We check if the mouse is over a panel/ */ - container = thisObject.panelsSpace.getContainer(point); + container = thisObject.panelsSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseClick', point); - return; - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseClick', point) + return + } /* We check if the mouse is over a floatingObject/ */ - let floatingObjectBeingClicked = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y); + let floatingObjectBeingClicked = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y) - if (floatingObjectBeingClicked >= 0) { + if (floatingObjectBeingClicked >= 0) { + let floatingObject = thisObject.floatingSpace.floatingLayer.getFloatingObject(undefined, floatingObjectBeingClicked) + floatingObject.eventHandler.raiseEvent('onMouseClick', point) - let floatingObject = thisObject.floatingSpace.floatingLayer.getFloatingObject(undefined, floatingObjectBeingClicked); - floatingObject.eventHandler.raiseEvent('onMouseClick', point); - - return; - - } + return + } /* If it is not, then we check if it is over any of the existing containers at the Chart Space. */ - container = thisObject.chartSpace.getContainer(point); + container = thisObject.chartSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseClick', point); - return; - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onMouseClick -> err = " + err); } - - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseClick', point) + return + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onMouseClick -> err = ' + err) } } + } - function onMouseUp(event) { + function onMouseUp (event) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onMouseUp -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] onMouseUp -> Entering function."); } - - if (containerDragStarted || viewPortBeingDragged || floatingObjectDragStarted) { - - thisObject.eventHandler.raiseEvent("Drag Finished", undefined); - - } + if (containerDragStarted || viewPortBeingDragged || floatingObjectDragStarted) { + thisObject.eventHandler.raiseEvent('Drag Finished', undefined) + } /* Turn off all the possible things that can be dragged. */ - containerDragStarted = false; - floatingObjectDragStarted = false; - viewPortBeingDragged = false; + containerDragStarted = false + floatingObjectDragStarted = false + viewPortBeingDragged = false - containerBeingDragged = undefined; + containerBeingDragged = undefined - browserCanvas.style.cursor = "auto"; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onMouseUp -> err = " + err); } - - } + browserCanvas.style.cursor = 'auto' + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onMouseUp -> err = ' + err) } } + } - function onMouseMove(event) { + function onMouseMove (event) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] onMouseMove -> Entering function.') } - try { + let point = { + x: event.pageX, + y: event.pageY - window.canvasApp.topMargin + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] onMouseMove -> Entering function."); } - - let point = { - x: event.pageX, - y: event.pageY - window.canvasApp.topMargin - }; - - viewPort.mousePosition.x = point.x; - viewPort.mousePosition.y = point.y; - - if (containerDragStarted === true || floatingObjectDragStarted === true || viewPortBeingDragged === true) { - - if (floatingObjectDragStarted === true) { - - if (thisObject.floatingSpace.floatingLayer.isInsideFloatingObject(floatingObjectBeingDragged, point.x, point.y) === false) { + viewPort.mousePosition.x = point.x + viewPort.mousePosition.y = point.y + if (containerDragStarted === true || floatingObjectDragStarted === true || viewPortBeingDragged === true) { + if (floatingObjectDragStarted === true) { + if (thisObject.floatingSpace.floatingLayer.isInsideFloatingObject(floatingObjectBeingDragged, point.x, point.y) === false) { /* This means that the user stop moving the mouse and the floatingObject floatingObject out of the pointer. In this case we cancell the drag operation . */ - floatingObjectDragStarted = false; - browserCanvas.style.cursor = "auto"; - return; - } - - } - - dragVector.upX = point.x; - dragVector.upY = point.y; - - checkDrag(event); - } else { - - onMouseOver(event); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onMouseMove -> err = " + err); } - + floatingObjectDragStarted = false + browserCanvas.style.cursor = 'auto' + return + } } + + dragVector.upX = point.x + dragVector.upY = point.y + + checkDrag(event) + } else { + onMouseOver(event) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onMouseMove -> err = ' + err) } } + } - function onMouseOver(event) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] onMouseOver -> Entering function."); } + function onMouseOver (event) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onMouseOver -> Entering function.') } /* First we raise the event signaling theat the mouse is potentially over another item, so that the current item can turn itself off. */ - thisObject.eventHandler.raiseEvent("onMouseNotOver"); + thisObject.eventHandler.raiseEvent('onMouseNotOver') /* Then we check who is the current object underneeth the mounse. */ - let point = { - x: event.pageX, - y: event.pageY - window.canvasApp.topMargin - }; + let point = { + x: event.pageX, + y: event.pageY - window.canvasApp.topMargin + } - let container; + let container /* We check if the mouse is over an element of the Top Space / */ - container = thisObject.topSpace.getContainer(point); + container = thisObject.topSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseOver', point); - return; - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseOver', point) + return + } /* We check if the mouse is over an element of the Bottom Space / */ - container = thisObject.bottomSpace.getContainer(point); + container = thisObject.bottomSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseOver', point); - return; - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseOver', point) + return + } /* We check if the mouse is over a panel/ */ - container = thisObject.panelsSpace.getContainer(point); + container = thisObject.panelsSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseOver', point); - return; - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseOver', point) + return + } /* We check if the mouse is over a floatingObject/ */ - let floatingObjectBeingClicked = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y); + let floatingObjectBeingClicked = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y) - if (floatingObjectBeingClicked >= 0) { + if (floatingObjectBeingClicked >= 0) { + let floatingObject = thisObject.floatingSpace.floatingLayer.getFloatingObject(undefined, floatingObjectBeingClicked) + floatingObject.eventHandler.raiseEvent('onMouseOver', point) - let floatingObject = thisObject.floatingSpace.floatingLayer.getFloatingObject(undefined, floatingObjectBeingClicked); - floatingObject.eventHandler.raiseEvent('onMouseOver', point); - - return; - - } + return + } /* If it is not, then we check if it is over any of the existing containers at the Chart Space. */ - container = thisObject.chartSpace.getContainer(point); + container = thisObject.chartSpace.getContainer(point) - if (container !== undefined && container.isClickeable === true) { - - container.eventHandler.raiseEvent('onMouseOver', point); - return; - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onMouseOver -> err = " + err); } - - } + if (container !== undefined && container.isClickeable === true) { + container.eventHandler.raiseEvent('onMouseOver', point) + return + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onMouseOver -> err = ' + err) } } + } - function onMouseWheel(event) { + function onMouseWheel (event) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onMouseWheel -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] onMouseWheel -> Entering function."); } - - // cross-browser wheel delta - var event = window.event || event; // old IE support - let delta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail)); + // cross-browser wheel delta + var event = window.event || event // old IE support + let delta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail)) /* We try first with panels. */ - let point = { - x: event.pageX, - y: event.pageY - window.canvasApp.topMargin - }; + let point = { + x: event.pageX, + y: event.pageY - window.canvasApp.topMargin + } - let panelContainer = canvas.panelsSpace.getContainer({ x: point.x, y: point.y }); + let panelContainer = canvas.panelsSpace.getContainer({ x: point.x, y: point.y }) - if (panelContainer !== undefined && panelContainer.isWheelable === true) { - - panelContainer.eventHandler.raiseEvent("Mouse Wheel", event.wheelDelta); - return false; // This instructs the browser not to take the event and scroll the page. - } + if (panelContainer !== undefined && panelContainer.isWheelable === true) { + panelContainer.eventHandler.raiseEvent('Mouse Wheel', event.wheelDelta) + return false // This instructs the browser not to take the event and scroll the page. + } /* We try second with floating objects. */ - let floatingObjectIndex = canvas.floatingSpace.floatingLayer.isInside(point.x, point.y); + let floatingObjectIndex = canvas.floatingSpace.floatingLayer.isInside(point.x, point.y) - if (floatingObjectIndex > 0) { - - canvas.floatingSpace.floatingLayer.changeTargetRepulsion(event.wheelDelta); - return false; // This instructs the browser not to take the event and scroll the page. - } + if (floatingObjectIndex > 0) { + canvas.floatingSpace.floatingLayer.changeTargetRepulsion(event.wheelDelta) + return false // This instructs the browser not to take the event and scroll the page. + } /* We try the Bottom Space. */ - let bottomContainer = canvas.bottomSpace.getContainer({ x: point.x, y: point.y }); + let bottomContainer = canvas.bottomSpace.getContainer({ x: point.x, y: point.y }) - if (bottomContainer !== undefined && bottomContainer.isWheeleable === true) { - - bottomContainer.eventHandler.raiseEvent("Mouse Wheel", event.wheelDelta); - return false; // This instructs the browser not to take the event and scroll the page. - - } + if (bottomContainer !== undefined && bottomContainer.isWheeleable === true) { + bottomContainer.eventHandler.raiseEvent('Mouse Wheel', event.wheelDelta) + return false // This instructs the browser not to take the event and scroll the page. + } /* Finally we try the Chart Space. */ - let chartContainer = canvas.chartSpace.getContainer({ x: point.x, y: point.y }); - - if (chartContainer !== undefined && chartContainer.isWheeleable === true) { - - chartContainer.eventHandler.raiseEvent("Mouse Wheel", event.wheelDelta); - return false; // This instructs the browser not to take the event and scroll the page. - - } else { + let chartContainer = canvas.chartSpace.getContainer({ x: point.x, y: point.y }) + if (chartContainer !== undefined && chartContainer.isWheeleable === true) { + chartContainer.eventHandler.raiseEvent('Mouse Wheel', event.wheelDelta) + return false // This instructs the browser not to take the event and scroll the page. + } else { /* If all the above fails, we fallback into applying zoom to the viewPort */ - viewPort.applyZoom(delta); - return false; // This instructs the browser not to take the event and scroll the page. - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onMouseWheel -> err = " + err); } - - } + viewPort.applyZoom(delta) + return false // This instructs the browser not to take the event and scroll the page. + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onMouseWheel -> err = ' + err) } } + } - function checkDrag(event) { + function checkDrag (event) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] checkDrag -> Entering function.') } - try { + if (containerDragStarted === true || floatingObjectDragStarted === true || viewPortBeingDragged === true) { + let point = { + x: event.pageX, + y: event.pageY - window.canvasApp.topMargin + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] checkDrag -> Entering function."); } + browserCanvas.style.cursor = 'grabbing' + thisObject.eventHandler.raiseEvent('Dragging', undefined) - if (containerDragStarted === true || floatingObjectDragStarted === true || viewPortBeingDragged === true) { + let targetFloatingObject = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y) - let point = { - x: event.pageX, - y: event.pageY - window.canvasApp.topMargin - }; + if (floatingObjectDragStarted) { + let floatingObject = thisObject.floatingSpace.floatingLayer.getFloatingObject(undefined, floatingObjectBeingDragged) - browserCanvas.style.cursor = "grabbing"; - thisObject.eventHandler.raiseEvent("Dragging", undefined); - - let targetFloatingObject = thisObject.floatingSpace.floatingLayer.isInside(point.x, point.y); - - if (floatingObjectDragStarted) { - - let floatingObject = thisObject.floatingSpace.floatingLayer.getFloatingObject(undefined, floatingObjectBeingDragged); - - floatingObject.currentPosition.x = dragVector.upX; - floatingObject.currentPosition.y = dragVector.upY; - - } - - if (containerDragStarted || viewPortBeingDragged) { + floatingObject.currentPosition.x = dragVector.upX + floatingObject.currentPosition.y = dragVector.upY + } + if (containerDragStarted || viewPortBeingDragged) { /* The parameters received have been captured with zoom applied. We must remove the zoom in order to correctly modify the displacement. */ + let downCopy = { + x: dragVector.downX, + y: dragVector.downY + } - let downCopy = { - x: dragVector.downX, - y: dragVector.downY - }; + let downCopyNoTransf + downCopyNoTransf = viewPort.unzoomThisPoint(downCopy) + // downCopyNoTransf = containerBeingDragged.zoom.unzoomThisPoint(downCopyNoTransf); - let downCopyNoTransf; - downCopyNoTransf = viewPort.unzoomThisPoint(downCopy); - //downCopyNoTransf = containerBeingDragged.zoom.unzoomThisPoint(downCopyNoTransf); + let upCopy = { + x: dragVector.upX, + y: dragVector.upY + } - let upCopy = { - x: dragVector.upX, - y: dragVector.upY - }; + let upCopyNoTranf + upCopyNoTranf = viewPort.unzoomThisPoint(upCopy) - let upCopyNoTranf; - upCopyNoTranf = viewPort.unzoomThisPoint(upCopy); + let displaceVector = { + x: dragVector.upX - dragVector.downX, + y: dragVector.upY - dragVector.downY + } - let displaceVector = { - x: dragVector.upX - dragVector.downX, - y: dragVector.upY - dragVector.downY - }; + if (viewPortBeingDragged) { + viewPort.displace(displaceVector) + } - if (viewPortBeingDragged) { - - viewPort.displace(displaceVector); - - } - - if (containerBeingDragged !== undefined) { - - containerBeingDragged.frame.position.x = containerBeingDragged.frame.position.x + displaceVector.x; - containerBeingDragged.frame.position.y = containerBeingDragged.frame.position.y + displaceVector.y; - - } - } + if (containerBeingDragged !== undefined) { + containerBeingDragged.frame.position.x = containerBeingDragged.frame.position.x + displaceVector.x + containerBeingDragged.frame.position.y = containerBeingDragged.frame.position.y + displaceVector.y + } + } /* Finally we set the starting point of the new dragVector at this current point. */ - dragVector.downX = dragVector.upX; - dragVector.downY = dragVector.upY; - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] checkDrag -> err = " + err); } - - } + dragVector.downX = dragVector.upX + dragVector.downY = dragVector.upY + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] checkDrag -> err = ' + err) } } -} \ No newline at end of file + } +} diff --git a/ChartUtilities.js b/ChartUtilities.js index 3f0b9ce02..6a2c91389 100644 --- a/ChartUtilities.js +++ b/ChartUtilities.js @@ -1,150 +1,142 @@ - -function getSideDays(timePeriod) { +function getSideDays (timePeriod) { + let daysOnSides - let daysOnSides; + if (timePeriod < _1_HOUR_IN_MILISECONDS) { + daysOnSides = 1 + } - if (timePeriod < _1_HOUR_IN_MILISECONDS) { - daysOnSides = 1; - } + if (timePeriod === _1_HOUR_IN_MILISECONDS) { + daysOnSides = 9 + } - if (timePeriod === _1_HOUR_IN_MILISECONDS) { - daysOnSides = 9; - } + if (timePeriod === _2_HOURS_IN_MILISECONDS) { + daysOnSides = 10 + } - if (timePeriod === _2_HOURS_IN_MILISECONDS) { - daysOnSides = 10; - } + if (timePeriod === _3_HOURS_IN_MILISECONDS) { + daysOnSides = 12 + } - if (timePeriod === _3_HOURS_IN_MILISECONDS) { - daysOnSides = 12; - } + if (timePeriod === _4_HOURS_IN_MILISECONDS) { + daysOnSides = 20 + } - if (timePeriod === _4_HOURS_IN_MILISECONDS) { - daysOnSides = 20; - } + if (timePeriod === _6_HOURS_IN_MILISECONDS) { + daysOnSides = 35 + } - if (timePeriod === _6_HOURS_IN_MILISECONDS) { - daysOnSides = 35; - } + if (timePeriod === _8_HOURS_IN_MILISECONDS) { + daysOnSides = 44 + } - if (timePeriod === _8_HOURS_IN_MILISECONDS) { - daysOnSides = 44; - } + if (timePeriod === _12_HOURS_IN_MILISECONDS) { + daysOnSides = 56 + } - if (timePeriod === _12_HOURS_IN_MILISECONDS) { - daysOnSides = 56; - } + if (timePeriod === ONE_DAY_IN_MILISECONDS) { + daysOnSides = 154 + } - if (timePeriod === ONE_DAY_IN_MILISECONDS) { - daysOnSides = 154; - } - - return daysOnSides; + return daysOnSides } - -function getCondenseFactor(timePeriod) { - - switch (timePeriod) { - case _1_MINUTE_IN_MILISECONDS: return 1; - case _5_MINUTES_IN_MILISECONDS: return 5; - case _10_MINUTES_IN_MILISECONDS: return 10; - case _30_MINUTES_IN_MILISECONDS: return 50; - case _1_HOUR_IN_MILISECONDS: return 100; - } +function getCondenseFactor (timePeriod) { + switch (timePeriod) { + case _1_MINUTE_IN_MILISECONDS: return 1 + case _5_MINUTES_IN_MILISECONDS: return 5 + case _10_MINUTES_IN_MILISECONDS: return 10 + case _30_MINUTES_IN_MILISECONDS: return 50 + case _1_HOUR_IN_MILISECONDS: return 100 + } } - -function getTransparenceFactor(timePeriod) { - - switch (timePeriod) { - case _1_MINUTE_IN_MILISECONDS: return "0.12"; - case _5_MINUTES_IN_MILISECONDS: return "0.10"; - case _10_MINUTES_IN_MILISECONDS: return "0.08"; - case _30_MINUTES_IN_MILISECONDS: return "0.06"; - case _1_HOUR_IN_MILISECONDS: return "0.04"; - } +function getTransparenceFactor (timePeriod) { + switch (timePeriod) { + case _1_MINUTE_IN_MILISECONDS: return '0.12' + case _5_MINUTES_IN_MILISECONDS: return '0.10' + case _10_MINUTES_IN_MILISECONDS: return '0.08' + case _30_MINUTES_IN_MILISECONDS: return '0.06' + case _1_HOUR_IN_MILISECONDS: return '0.04' + } } +function recalculatePeriod (zoomLevel) { + // console.log(" recalculatePeriod > " + zoomLevel); -function recalculatePeriod(zoomLevel) { + if (zoomLevel > 200) { + return _1_MINUTE_IN_MILISECONDS + } - //console.log(" recalculatePeriod > " + zoomLevel); + if (zoomLevel > 120) { + return _2_MINUTES_IN_MILISECONDS + } - if (zoomLevel > 200) { - return _1_MINUTE_IN_MILISECONDS; - } + if (zoomLevel > 80) { + return _3_MINUTES_IN_MILISECONDS + } - if (zoomLevel > 120) { - return _2_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > 60) { + return _4_MINUTES_IN_MILISECONDS + } - if (zoomLevel > 80) { - return _3_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > 15) { + return _5_MINUTES_IN_MILISECONDS + } - if (zoomLevel > 60) { - return _4_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -7) { + return _10_MINUTES_IN_MILISECONDS + } - if (zoomLevel > 15) { - return _5_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -10) { + return _15_MINUTES_IN_MILISECONDS + } - if (zoomLevel > - 7) { - return _10_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -13) { + return _20_MINUTES_IN_MILISECONDS + } - if (zoomLevel > - 10) { - return _15_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -15) { + return _30_MINUTES_IN_MILISECONDS + } - if (zoomLevel > - 13) { - return _20_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -16) { + return _40_MINUTES_IN_MILISECONDS + } - if (zoomLevel > - 15) { - return _30_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -17) { + return _45_MINUTES_IN_MILISECONDS + } - if (zoomLevel > - 16) { - return _40_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -18) { + return _1_HOUR_IN_MILISECONDS + } - if (zoomLevel > - 17) { - return _45_MINUTES_IN_MILISECONDS; - } + if (zoomLevel > -24) { + return _2_HOURS_IN_MILISECONDS + } - if (zoomLevel > - 18) { - return _1_HOUR_IN_MILISECONDS; - } + if (zoomLevel > -25) { + return _3_HOURS_IN_MILISECONDS + } - if (zoomLevel > - 24) { - return _2_HOURS_IN_MILISECONDS; - } + if (zoomLevel > -27) { + return _4_HOURS_IN_MILISECONDS + } - if (zoomLevel > - 25) { - return _3_HOURS_IN_MILISECONDS; - } + if (zoomLevel > -27.5) { + return _6_HOURS_IN_MILISECONDS + } - if (zoomLevel > - 27) { - return _4_HOURS_IN_MILISECONDS; - } + if (zoomLevel > -27.75) { + return _8_HOURS_IN_MILISECONDS + } - if (zoomLevel > - 27.5) { - return _6_HOURS_IN_MILISECONDS; - } + if (zoomLevel > -28) { + return _12_HOURS_IN_MILISECONDS + } - if (zoomLevel > - 27.75) { - return _8_HOURS_IN_MILISECONDS; - } - - if (zoomLevel > - 28) { - return _12_HOURS_IN_MILISECONDS; - } - - if (zoomLevel <= - 28) { - return ONE_DAY_IN_MILISECONDS; - } + if (zoomLevel <= -28) { + return ONE_DAY_IN_MILISECONDS + } } diff --git a/CloudVM/CloudRequire.js b/CloudVM/CloudRequire.js index 464f72391..5214030e4 100644 --- a/CloudVM/CloudRequire.js +++ b/CloudVM/CloudRequire.js @@ -1,61 +1,49 @@ -function newCloudRequire(bot, logger) { + function newCloudRequire (bot, logger) { + const INFO_LOG = true + const LOG_FILE_CONTENT = false - const INFO_LOG = true; - const LOG_FILE_CONTENT = false; + const MODULE_NAME = 'Cloud Require' - const MODULE_NAME = "Cloud Require"; + let thisObject = { + downloadBot: downloadBot, + downloadCommons: downloadCommons + } - let thisObject = { - downloadBot: downloadBot, - downloadCommons: downloadCommons - }; + return thisObject - return thisObject; + function downloadBot (pCloudStorage, pFilePath, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write(MODULE_NAME, '[INFO] downloadBot -> Entering function.') } - function downloadBot(pCloudStorage, pFilePath, callBackFunction) { + let filePath = window.canvasApp.urlPrefix + 'Bots' + '/' + pFilePath + '/' + 'User.Bot.js' - try { + downloadModule(filePath, onDownloaded) - if (INFO_LOG === true) { logger.write(MODULE_NAME, "[INFO] downloadBot -> Entering function."); } + function onDownloaded (pModule) { + callBackFunction(window.DEFAULT_OK_RESPONSE, pModule) + return + } + } catch (err) { + logger.write(MODULE_NAME, '[ERROR] downloadBot -> err = ' + err.message) + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } + } - let filePath = window.canvasApp.urlPrefix + "Bots" + "/" + pFilePath + "/" + "User.Bot.js"; + function downloadCommons (pCloudStorage, pFilePath, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write(MODULE_NAME, '[INFO] downloadCommons -> Entering function.') } - downloadModule(filePath, onDownloaded) + let filePath = window.canvasApp.urlPrefix + 'Bots' + '/' + pFilePath + '/' + 'Commons.js' - function onDownloaded(pModule) { + downloadModule(filePath, onDownloaded) - callBackFunction(window.DEFAULT_OK_RESPONSE, pModule); - return; - - } - - } catch (err) { - logger.write(MODULE_NAME, "[ERROR] downloadBot -> err = " + err.message); - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - } - } - - function downloadCommons(pCloudStorage, pFilePath, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write(MODULE_NAME, "[INFO] downloadCommons -> Entering function."); } - - let filePath = window.canvasApp.urlPrefix + "Bots" + "/" + pFilePath + "/" + "Commons.js"; - - downloadModule(filePath, onDownloaded) - - function onDownloaded(pModule) { - - callBackFunction(window.DEFAULT_OK_RESPONSE, pModule); - return; - - } - - } catch (err) { - logger.write(MODULE_NAME, "[ERROR] downloadCommons -> err = " + err.message); - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - } - } - -}; \ No newline at end of file + function onDownloaded (pModule) { + callBackFunction(window.DEFAULT_OK_RESPONSE, pModule) + return + } + } catch (err) { + logger.write(MODULE_NAME, '[ERROR] downloadCommons -> err = ' + err.message) + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } + } + }; diff --git a/CloudVM/CloudSupport.js b/CloudVM/CloudSupport.js index a494e7e39..3c91c1403 100644 --- a/CloudVM/CloudSupport.js +++ b/CloudVM/CloudSupport.js @@ -1,4 +1,4 @@ - +  /* This module is for enabling the AACloud to run at the browser. @@ -7,137 +7,115 @@ When running at the clode on NodeJS some things work diffently that at the brows */ -function webRequire(pModulePath) { +function webRequire (pModulePath) { + switch (pModulePath) { - switch (pModulePath) { + case './AzureStorage': { + let MODULE = {} + MODULE.newAzureStorage = newAzureStorage + return MODULE - case './AzureStorage': { - - let MODULE = {}; - MODULE.newAzureStorage = newAzureStorage; - return MODULE; - - function newAzureStorage() { - - return AzureStorage.Blob; - - } - } - case './EventHandler': { - - let MODULE = {}; - MODULE.newEventHandler = newEventHandler; - return MODULE; - } - case './BlobStorage': { - - let MODULE = {}; - MODULE.newBlobStorage = newBlobStorage; - return MODULE; - } - case './DebugLog': { - - let MODULE = {}; - MODULE.newDebugLog = newDebugLog; - return MODULE; - } - case './TradingBotProcessMainLoop': { - - let MODULE = {}; - MODULE.newTradingBotProcessMainLoop = newTradingBotProcessMainLoop; - return MODULE; - } - case './ExtractionBotProcessMainLoop': { - - let MODULE = {}; - MODULE.newExtractionBotProcessMainLoop = newExtractionBotProcessMainLoop; - return MODULE; - } - case './IndicatorBotProcessMainLoop': { - - let MODULE = {}; - MODULE.newIndicatorBotProcessMainLoop = newIndicatorBotProcessMainLoop; - return MODULE; - } - case './CloudUtilities': { - - let MODULE = {}; - MODULE.newCloudUtilities = newCloudUtilities; - return MODULE; - } - case './PoloniexAPIClient': { - - let MODULE = {}; - MODULE.newPoloniexAPIClient = newPoloniexAPIClient; - return MODULE; - } - case './Exchange/ExchangeAPI': { - - let MODULE = {}; - MODULE.newExchangeAPI = newExchangeAPI; - return MODULE; - } - case './Context': { - - let MODULE = {}; - MODULE.newContext = newContext; - return MODULE; - } - case './Assistant': { - - let MODULE = {}; - MODULE.newAssistant = newAssistant; - return MODULE; - } - case './StatusReport': { - - let MODULE = {}; - MODULE.newStatusReport = newStatusReport; - return MODULE; - } - case './DataSet': { - - let MODULE = {}; - MODULE.newDataSet = newDataSet; - return MODULE; - } - case './StatusDependencies': { - - let MODULE = {}; - MODULE.newStatusDependencies = newStatusDependencies; - return MODULE; - } - case './DataDependencies': { - - let MODULE = {}; - MODULE.newDataDependencies = newDataDependencies; - return MODULE; - } - case './CloudRequire': { - - let MODULE = {}; - MODULE.newCloudRequire = newCloudRequire; - return MODULE; - } - default: { - console.log(pModulePath + " not found. "); - } + function newAzureStorage () { + return AzureStorage.Blob + } } + case './EventHandler': { + let MODULE = {} + MODULE.newEventHandler = newEventHandler + return MODULE + } + case './BlobStorage': { + let MODULE = {} + MODULE.newBlobStorage = newBlobStorage + return MODULE + } + case './DebugLog': { + let MODULE = {} + MODULE.newDebugLog = newDebugLog + return MODULE + } + case './TradingBotProcessMainLoop': { + let MODULE = {} + MODULE.newTradingBotProcessMainLoop = newTradingBotProcessMainLoop + return MODULE + } + case './ExtractionBotProcessMainLoop': { + let MODULE = {} + MODULE.newExtractionBotProcessMainLoop = newExtractionBotProcessMainLoop + return MODULE + } + case './IndicatorBotProcessMainLoop': { + let MODULE = {} + MODULE.newIndicatorBotProcessMainLoop = newIndicatorBotProcessMainLoop + return MODULE + } + case './CloudUtilities': { + let MODULE = {} + MODULE.newCloudUtilities = newCloudUtilities + return MODULE + } + case './PoloniexAPIClient': { + let MODULE = {} + MODULE.newPoloniexAPIClient = newPoloniexAPIClient + return MODULE + } + case './Exchange/ExchangeAPI': { + let MODULE = {} + MODULE.newExchangeAPI = newExchangeAPI + return MODULE + } + case './Context': { + let MODULE = {} + MODULE.newContext = newContext + return MODULE + } + case './Assistant': { + let MODULE = {} + MODULE.newAssistant = newAssistant + return MODULE + } + case './StatusReport': { + let MODULE = {} + MODULE.newStatusReport = newStatusReport + return MODULE + } + case './DataSet': { + let MODULE = {} + MODULE.newDataSet = newDataSet + return MODULE + } + case './StatusDependencies': { + let MODULE = {} + MODULE.newStatusDependencies = newStatusDependencies + return MODULE + } + case './DataDependencies': { + let MODULE = {} + MODULE.newDataDependencies = newDataDependencies + return MODULE + } + case './CloudRequire': { + let MODULE = {} + MODULE.newCloudRequire = newCloudRequire + return MODULE + } + default: { + console.log(pModulePath + ' not found. ') + } + } } -function downloadModule(pPath, callBackFunction) { - +function downloadModule (pPath, callBackFunction) { /* We will need this to load individual bots modules. */ - REQUIREJS([pPath], onRequired); + REQUIREJS([pPath], onRequired) - function onRequired(pModule) { + function onRequired (pModule) { + console.log('CloudVM ' + pPath + ' downloaded.') - console.log("CloudVM " + pPath + " downloaded."); - - let MODULE = {}; - MODULE.newUserBot = newUserBot; - callBackFunction(MODULE); - } + let MODULE = {} + MODULE.newUserBot = newUserBot + callBackFunction(MODULE) + } } diff --git a/CloudVM/CloudVM.js b/CloudVM/CloudVM.js index fdd5379db..4fc7fa8ce 100644 --- a/CloudVM/CloudVM.js +++ b/CloudVM/CloudVM.js @@ -1,152 +1,129 @@ - -function newCloudVM() { +  +function newCloudVM () { + const MODULE_NAME = 'CloudVM' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "CloudVM"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + var thisObject = { + onBotPlayPressed: onBotPlayPressed, + onBotStopPressed: onBotStopPressed + } - var thisObject = { - onBotPlayPressed: onBotPlayPressed, - onBotStopPressed: onBotStopPressed - }; + let root = newRoot() + let intervalHandler + let previousBotCode = '' + let errorsCheckingForBotCodeChanges = 0 - let root = newRoot(); - let intervalHandler; - let previousBotCode = ""; - let errorsCheckingForBotCodeChanges = 0; + return thisObject - return thisObject; + function onBotPlayPressed (pUI_COMMANDS) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onBotPlayPressed -> Entering function.') } - function onBotPlayPressed(pUI_COMMANDS) { + window.SHALL_BOT_STOP = false + errorsCheckingForBotCodeChanges = 0 - try { + window.CURRENT_ENVIRONMENT = 'Develop' + window.CURRENT_EXECUTION_AT = 'Browser' + window.STORAGE_PERMISSIONS = ecosystem.getStoragePermissions() - if (INFO_LOG === true) { logger.write("[INFO] onBotPlayPressed -> Entering function."); } - - window.SHALL_BOT_STOP = false; - errorsCheckingForBotCodeChanges = 0; - - window.CURRENT_ENVIRONMENT = "Develop"; - window.CURRENT_EXECUTION_AT = "Browser"; - window.STORAGE_PERMISSIONS = ecosystem.getStoragePermissions(); - - window.EXCHANGE_NAME = "Poloniex"; - window.MARKET = { - assetA: "USDT", - assetB: "BTC" - }; + window.EXCHANGE_NAME = 'Poloniex' + window.MARKET = { + assetA: 'USDT', + assetB: 'BTC' + } /* When running at the browser, the AACloud VM will look for this data, in this case it does not contain any key or secret, since the browser only know the session token the user received when he logged in. */ - window.EXCHANGE_KEYS = { - Poloniex: { - Key: "", - Secret: "" - } - } - - root.initialize(pUI_COMMANDS, onInitialized); - - function onInitialized() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] onBotPlayPressed -> Entering function."); } - - root.start(); - - intervalHandler = setInterval(checkForChangesInBotCode, 10000); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onBotPlayPressed -> onInitialized -> err.message = " + err.message); } - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onBotPlayPressed -> err.message = " + err.message); } + window.EXCHANGE_KEYS = { + Poloniex: { + Key: '', + Secret: '' } - } + } - function onBotStopPressed() { - - if (INFO_LOG === true) { logger.write("[INFO] onBotStopPressed -> Entering function."); } - - window.SHALL_BOT_STOP = true; - errorsCheckingForBotCodeChanges = 0; - - } - - function checkForChangesInBotCode() { + root.initialize(pUI_COMMANDS, onInitialized) + function onInitialized () { try { + if (INFO_LOG === true) { logger.write('[INFO] onBotPlayPressed -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] checkForChangesInBotCode -> Entering function."); } - - let botFunction = newUserBot; - - if (botFunction !== undefined) { - - let currentBotCode = botFunction.toString(); - - if (previousBotCode !== "") { - - if (currentBotCode !== previousBotCode) { - - console.log("CloudVM -> Bot code changes detected."); - - let path = window.canvasApp.urlPrefix - + "AABrowserAPI" + "/" - + "saveBotCode" + "/" - + window.DEV_TEAM + "/" - + "members" + "/" - + window.USER_LOGGED_IN + "/" - + window.CURRENT_BOT_REPO + "/" - + window.CURRENT_PROCESS + "/" - + "User.Bot.js" - ; - - callServer(currentBotCode, path, onServerResponse); - - function onServerResponse(err) { - - err = JSON.parse(err); - - if (INFO_LOG === true) { logger.write("[INFO] checkForChangesInBotCode -> onServerResponse -> Entering function."); } - - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { - - if (ERROR_LOG === true) { logger.write("[ERROR] checkForChangesInBotCode -> onServerResponse -> err.message = " + err.message); } - console.log("CloudVM -> Changes in code NOT saved. Plase check the error log and try again."); - return; - } - - console.log("CloudVM -> Changes in code saved."); - } - } - } - - previousBotCode = currentBotCode; - } + root.start() + intervalHandler = setInterval(checkForChangesInBotCode, 10000) } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] checkForChangesInBotCode -> err.message = " + err.message); } - errorsCheckingForBotCodeChanges++; - - if (errorsCheckingForBotCodeChanges > 2) { - - if (ERROR_LOG === true) { logger.write("[ERROR] checkForChangesInBotCode -> Giving up."); } - - clearInterval(intervalHandler); - - } + if (ERROR_LOG === true) { logger.write('[ERROR] onBotPlayPressed -> onInitialized -> err.message = ' + err.message) } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onBotPlayPressed -> err.message = ' + err.message) } } -} \ No newline at end of file + } + + function onBotStopPressed () { + if (INFO_LOG === true) { logger.write('[INFO] onBotStopPressed -> Entering function.') } + + window.SHALL_BOT_STOP = true + errorsCheckingForBotCodeChanges = 0 + } + + function checkForChangesInBotCode () { + try { + if (INFO_LOG === true) { logger.write('[INFO] checkForChangesInBotCode -> Entering function.') } + + let botFunction = newUserBot + + if (botFunction !== undefined) { + let currentBotCode = botFunction.toString() + + if (previousBotCode !== '') { + if (currentBotCode !== previousBotCode) { + console.log('CloudVM -> Bot code changes detected.') + + let path = window.canvasApp.urlPrefix + + 'AABrowserAPI' + '/' + + 'saveBotCode' + '/' + + window.DEV_TEAM + '/' + + 'members' + '/' + + window.USER_LOGGED_IN + '/' + + window.CURRENT_BOT_REPO + '/' + + window.CURRENT_PROCESS + '/' + + 'User.Bot.js' + + callServer(currentBotCode, path, onServerResponse) + + function onServerResponse (err) { + err = JSON.parse(err) + + if (INFO_LOG === true) { logger.write('[INFO] checkForChangesInBotCode -> onServerResponse -> Entering function.') } + + if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + if (ERROR_LOG === true) { logger.write('[ERROR] checkForChangesInBotCode -> onServerResponse -> err.message = ' + err.message) } + console.log('CloudVM -> Changes in code NOT saved. Plase check the error log and try again.') + return + } + + console.log('CloudVM -> Changes in code saved.') + } + } + } + + previousBotCode = currentBotCode + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] checkForChangesInBotCode -> err.message = ' + err.message) } + errorsCheckingForBotCodeChanges++ + + if (errorsCheckingForBotCodeChanges > 2) { + if (ERROR_LOG === true) { logger.write('[ERROR] checkForChangesInBotCode -> Giving up.') } + + clearInterval(intervalHandler) + } + } + } +} diff --git a/CloudVM/WebFS.js b/CloudVM/WebFS.js index 347d69892..1ac6e2439 100644 --- a/CloudVM/WebFS.js +++ b/CloudVM/WebFS.js @@ -1,71 +1,64 @@ -function newWebFS() { - - const MODULE_NAME = "Web FS"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + function newWebFS () { + const MODULE_NAME = 'Web FS' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME /* - This is the module emulates the NodeJS 'fs'. + This is the module emulates the NodeJS 'fs'. */ - var thisObject = { - readFileSync: readFileSync, - appendFileSync: appendFileSync, - mkdirSync: mkdirSync, - statSync: statSync, - readdir: readdir, - readdirSync: readdirSync, - readFile: readFile - }; + var thisObject = { + readFileSync: readFileSync, + appendFileSync: appendFileSync, + mkdirSync: mkdirSync, + statSync: statSync, + readdir: readdir, + readdirSync: readdirSync, + readFile: readFile + } + return thisObject - return thisObject; + function readFileSync (pPath, pEncoding) { + switch (pPath) { - function readFileSync(pPath, pEncoding) { + case '': { + break + } + } + } - switch (pPath) { - - case '': { - - break; - } - } - } - - function appendFileSync(pPath, pText) { + function appendFileSync (pPath, pText) { /* We will ignore this since we can not and dont want to really write something on disk while we are at the browser. */ - } - - function readdir(pPath, callBackFunction) { + } + function readdir (pPath, callBackFunction) { /* We will return an empty array of files. */ - callBackFunction([]); - } + callBackFunction([]) + } - function readdirSync(pPath, callBackFunction) { + function readdirSync (pPath, callBackFunction) { + } - } - - function mkdirSync(pPath) { + function mkdirSync (pPath) { /* Again we do nothing. */ - } + } - function readFile(pPath) { + function readFile (pPath) { /* Again we do nothing. */ - } + } - function statSync(pPath) { - - let stats - stats.size = 0; - return stats - } -} \ No newline at end of file + function statSync (pPath) { + let stats + stats.size = 0 + return stats + } + } diff --git a/CompetitionStorage.js b/CompetitionStorage.js index 007d07253..9b4ce6c23 100644 --- a/CompetitionStorage.js +++ b/CompetitionStorage.js @@ -1,160 +1,136 @@ - -function newCompetitionStorage(pName) { +  +function newCompetitionStorage (pName) { + const MODULE_NAME = 'Competition Storage' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Competition Storage"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { - let thisObject = { + competitorsSequences: [], + eventHandler: undefined, + initialize: initialize - competitorsSequences: [], - eventHandler: undefined, - initialize: initialize + } - } - - thisObject.eventHandler = newEventHandler(); + thisObject.eventHandler = newEventHandler() /* We name the event Handler to easy debugging. */ - thisObject.eventHandler.name = "Storage-" + pName; + thisObject.eventHandler.name = 'Storage-' + pName - let fileSequences = []; + let fileSequences = [] - return thisObject; + return thisObject - function initialize(pHost, pCompetition, pExchange, pMarket, callBackFunction) { + function initialize (pHost, pCompetition, pExchange, pMarket, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pHost.codeName + '-' + pCompetition.codeName) } - try { + let dataSetsToLoad = 0 + let dataSetsLoaded = 0 - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pHost.codeName + "-" + pCompetition.codeName); } + fileSequences = [] - let dataSetsToLoad = 0; - let dataSetsLoaded = 0; + for (let j = 0; j < pCompetition.participants.length; j++) { + let devTeam = ecosystem.getTeam(pCompetition.participants[j].devTeam) + let bot = ecosystem.getBot(devTeam, pCompetition.participants[j].bot) + let product = ecosystem.getProduct(bot, 'Competition Trading History') - fileSequences = []; + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + devTeam.codeName + '-' + bot.codeName + '-' + product.codeName) } - for (let j = 0; j < pCompetition.participants.length; j++) { + for (let i = 0; i < product.dataSets.length; i++) { + let thisSet = product.dataSets[i] - let devTeam = ecosystem.getTeam(pCompetition.participants[j].devTeam); - let bot = ecosystem.getBot(devTeam, pCompetition.participants[j].bot) - let product = ecosystem.getProduct(bot, "Competition Trading History"); + switch (thisSet.type) { + case 'File Sequence': { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> File Sequence -> key = ' + pHost.codeName + '-' + pCompetition.codeName + '-' + devTeam.codeName + '-' + bot.codeName + '-' + product.codeName) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + devTeam.codeName + "-" + bot.codeName + "-" + product.codeName); } + let fileSequence = newFileSequence() + fileSequence.initialize(devTeam, bot, product, thisSet, pExchange, pMarket, onFileSequenceReady) + fileSequences.push(fileSequence) + dataSetsToLoad++ + } + break + } - for (let i = 0; i < product.dataSets.length; i++) { + function onFileSequenceReady (err, pCaller) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> key = ' + pHost.codeName + '-' + pCompetition.codeName + '-' + devTeam.codeName + '-' + bot.codeName + '-' + product.codeName) } - let thisSet = product.dataSets[i]; - - switch (thisSet.type) { - case 'File Sequence': { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> File Sequence -> key = " + pHost.codeName + "-" + pCompetition.codeName + "-" + devTeam.codeName + "-" + bot.codeName + "-" + product.codeName); } - - let fileSequence = newFileSequence(); - fileSequence.initialize(devTeam, bot, product, thisSet, pExchange, pMarket, onFileSequenceReady); - fileSequences.push(fileSequence); - dataSetsToLoad++; - } - break; - } - - function onFileSequenceReady(err, pCaller) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> key = " + pHost.codeName + "-" + pCompetition.codeName + "-" + devTeam.codeName + "-" + bot.codeName + "-" + product.codeName); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> err.message = " + err.message); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> This bot has not starting competing yet."); } - - break; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - let event = { - totalValue: pCaller.getExpectedFiles(), - currentValue: pCaller.getFilesLoaded() - } - - thisObject.eventHandler.raiseEvent('File Sequence Loaded', event); - - if (event.currentValue === event.totalValue) { - - dataSetsLoaded++; - - checkInitializeComplete(); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileSequenceReady -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function checkInitializeComplete() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] checkInitializeComplete -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] checkInitializeComplete -> key = " + pHost.codeName + "-" + pCompetition.codeName + "-" + devTeam.codeName + "-" + bot.codeName + "-" + product.codeName); } - - if (dataSetsLoaded === dataSetsToLoad) { - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> checkInitializeComplete -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received OK Response.') } + break } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> err.message = ' + err.message) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> This bot has not starting competing yet.') } + + break + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + let event = { + totalValue: pCaller.getExpectedFiles(), + currentValue: pCaller.getFilesLoaded() + } + + thisObject.eventHandler.raiseEvent('File Sequence Loaded', event) + + if (event.currentValue === event.totalValue) { + dataSetsLoaded++ + + checkInitializeComplete() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileSequenceReady -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - thisObject.competitorsSequences.push(fileSequences); + function checkInitializeComplete () { + try { + if (INFO_LOG === true) { logger.write('[INFO] checkInitializeComplete -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] checkInitializeComplete -> key = ' + pHost.codeName + '-' + pCompetition.codeName + '-' + devTeam.codeName + '-' + bot.codeName + '-' + product.codeName) } - if (pCompetition.participants.length === 0) { //If there are no competitions, respond OK - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); + if (dataSetsLoaded === dataSetsToLoad) { + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> checkInitializeComplete -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + } } - } + } + thisObject.competitorsSequences.push(fileSequences) + + if (pCompetition.participants.length === 0) { // If there are no competitions, respond OK + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } } diff --git a/Container.js b/Container.js index c35dfa52c..76eb3357f 100644 --- a/Container.js +++ b/Container.js @@ -1,36 +1,32 @@ - -function newContainer() { +function newContainer () { + var container = { + frame: undefined, + displacement: undefined, + eventHandler: undefined, + parentContainer: undefined, + isDraggeable: true, + isClickeable: false, + isWheelable: false, + name: undefined, + initialize: initialize + } - var container = { - frame: undefined, - displacement: undefined, - eventHandler: undefined, - parentContainer: undefined, - isDraggeable: true, - isClickeable: false, - isWheelable: false, - name: undefined, - initialize: initialize - }; + return container - return container; + function initialize () { + var frame = newFrame() + frame.initialize() + this.frame = frame + frame.container = container - function initialize() { + var eventHandler = newEventHandler() + eventHandler.initialize() + eventHandler.name = container.name + this.eventHandler = eventHandler - var frame = newFrame(); - frame.initialize(); - this.frame = frame; - frame.container = container; - - var eventHandler = newEventHandler(); - eventHandler.initialize(); - eventHandler.name = container.name; - this.eventHandler = eventHandler; - - var displacement = newDisplacement(); - this.displacement = displacement; - displacement.container = container; - - } -} \ No newline at end of file + var displacement = newDisplacement() + this.displacement = displacement + displacement.container = container + } +} diff --git a/Dashboard.js b/Dashboard.js index 0e98a9bff..0c2075efe 100644 --- a/Dashboard.js +++ b/Dashboard.js @@ -1,133 +1,105 @@ - -let canvas; -let markets; -let ecosystem = newEcosystem(); -let cloudVM = newCloudVM(); -let INITIAL_ZOOM_LEVEL = -26; // This is the zoom level at the view port in which the APP starts. -let INITIAL_TIME_PERIOD = recalculatePeriod(INITIAL_ZOOM_LEVEL); // This value will be overwritten at the viewPort.initialize if the user had a prevous session with this same browser. -let viewPort = newViewPort(); +  +let canvas +let markets +let ecosystem = newEcosystem() +let cloudVM = newCloudVM() +let INITIAL_ZOOM_LEVEL = -26 // This is the zoom level at the view port in which the APP starts. +let INITIAL_TIME_PERIOD = recalculatePeriod(INITIAL_ZOOM_LEVEL) // This value will be overwritten at the viewPort.initialize if the user had a prevous session with this same browser. +let viewPort = newViewPort() -function newDashboard() { +function newDashboard () { + const MODULE_NAME = 'Dashboard' + const INFO_LOG = false + const ERROR_LOG = true + const INTENSIVE_LOG = false + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Dashboard"; - const INFO_LOG = false; - const ERROR_LOG = true; - const INTENSIVE_LOG = false; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { + start: start + } - let thisObject = { - start: start - }; + const DEBUG_START_UP_DELAY = 0 // 3000; // This is a waiting time in case there is a need to debug the very first steps of initialization, to be able to hit F12 on time. - const DEBUG_START_UP_DELAY = 0; //3000; // This is a waiting time in case there is a need to debug the very first steps of initialization, to be able to hit F12 on time. + return thisObject - return thisObject; - - function start() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] start -> Entering function."); } + function start () { + try { + if (INFO_LOG === true) { logger.write('[INFO] start -> Entering function.') } /* Here we will setup the global eventHandler that will enable the Canvas App to react to events happening outside its execution scope. */ - window.canvasApp.eventHandler = newEventHandler(); - window.canvasApp.eventHandler.listenToEvent("User Profile Changed", userProfileChanged); - window.canvasApp.eventHandler.listenToEvent("Browser Resized", browserResized); + window.canvasApp.eventHandler = newEventHandler() + window.canvasApp.eventHandler.listenToEvent('User Profile Changed', userProfileChanged) + window.canvasApp.eventHandler.listenToEvent('Browser Resized', browserResized) - loadImages(onImagesLoaded); + loadImages(onImagesLoaded) - function onImagesLoaded() { + function onImagesLoaded () { + if (INFO_LOG === true) { logger.write('[INFO] start -> onImagesLoaded -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] start -> onImagesLoaded -> Entering function."); } + /* Next we start the App */ - /* Next we start the App*/ - - setTimeout(delayedStart, DEBUG_START_UP_DELAY); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] start -> err = " + err); } - - } + setTimeout(delayedStart, DEBUG_START_UP_DELAY) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] start -> err = ' + err) } } + } - - function delayedStart() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] delayedStart -> Entering function."); } + function delayedStart () { + try { + if (INFO_LOG === true) { logger.write('[INFO] delayedStart -> Entering function.') } /* For now, we are supporting only one market. */ - let market = { - id: 2, - assetA: "USDT", - assetB: "BTC" - }; + let market = { + id: 2, + assetA: 'USDT', + assetB: 'BTC' + } - markets = new Map(); + markets = new Map() - markets.set(market.id, market); + markets.set(market.id, market) - canvas = newCanvas(); - canvas.initialize(); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] delayedStart -> err = " + err); } - - } + canvas = newCanvas() + canvas.initialize() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] delayedStart -> err = ' + err) } } + } - function userProfileChanged() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] userProfileChanged -> Entering function."); } - - canvas.topSpace.initialize(); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] userProfileChanged -> err = " + err); } - - } + function userProfileChanged () { + try { + if (INFO_LOG === true) { logger.write('[INFO] userProfileChanged -> Entering function.') } + canvas.topSpace.initialize() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] userProfileChanged -> err = ' + err) } } + } - function browserResized() { + function browserResized () { + try { + if (INFO_LOG === true) { logger.write('[INFO] browserResized -> Entering function.') } - try { + browserCanvas = document.getElementById('canvas') - if (INFO_LOG === true) { logger.write("[INFO] browserResized -> Entering function."); } - - browserCanvas = document.getElementById('canvas'); - - browserCanvas.width = window.innerWidth; - browserCanvas.height = window.innerHeight - window.canvasApp.topMargin; - - viewPort.initialize(); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] browserResized -> err = " + err); } - - } + browserCanvas.width = window.innerWidth + browserCanvas.height = window.innerHeight - window.canvasApp.topMargin + viewPort.initialize() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] browserResized -> err = ' + err) } } + } - function loadImages(callBack) { + function loadImages (callBack) { + try { + if (INFO_LOG === true) { logger.write('[INFO] loadImages -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] loadImages -> Entering function."); } - - const accessToken = ""; + const accessToken = '' /* Soon, we will need to get images from the Financial Beings Module. I live this core here as a sample for that: @@ -187,25 +159,25 @@ function newDashboard() { */ - const networkInterfaceTeams = Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl - }); + const networkInterfaceTeams = Apollo.lib.createNetworkInterface({ + uri: window.canvasApp.graphQL.masterAppApiUrl + }) - networkInterfaceTeams.use([{ - applyMiddleware(req, next) { - req.options.headers = { - authorization: `Bearer ${accessToken}` - }; - next(); - } - }]); - - const apolloClientTeams = new Apollo.lib.ApolloClient({ - networkInterface: networkInterfaceTeams, - connectToDevTools: true, - }); + networkInterfaceTeams.use([{ + applyMiddleware (req, next) { + req.options.headers = { + authorization: `Bearer ${accessToken}` + } + next() + } + }]) - const ALL_TEAMS_QUERY = Apollo.gql` + const apolloClientTeams = new Apollo.lib.ApolloClient({ + networkInterface: networkInterfaceTeams, + connectToDevTools: true + }) + + const ALL_TEAMS_QUERY = Apollo.gql` { teams_Teams{ edges{ @@ -238,70 +210,59 @@ function newDashboard() { } ` - let teams; + let teams - const getTeams = () => { - return new Promise((resolve, reject) => { - apolloClientTeams.query({ - query: ALL_TEAMS_QUERY - }) + const getTeams = () => { + return new Promise((resolve, reject) => { + apolloClientTeams.query({ + query: ALL_TEAMS_QUERY + }) .then(response => { - teams = response.data.teams_Teams; - window.localStorage.setItem('Teams', JSON.stringify(response.data.teams_Teams)); - resolve({ teams: response.data.teams_Teams }) - }) + teams = response.data.teams_Teams + window.localStorage.setItem('Teams', JSON.stringify(response.data.teams_Teams)) + resolve({ teams: response.data.teams_Teams }) + }) .catch(err => { - if (ERROR_LOG === true) { logger.write("[ERROR] loadImages -> getTeams -> Error fetching data from Teams Module."); } - if (ERROR_LOG === true) { logger.write("[ERROR] loadImages -> getTeams -> err = " + err); } - reject(err) - }); - }) - } + if (ERROR_LOG === true) { logger.write('[ERROR] loadImages -> getTeams -> Error fetching data from Teams Module.') } + if (ERROR_LOG === true) { logger.write('[ERROR] loadImages -> getTeams -> err = ' + err) } + reject(err) + }) + }) + } // To avoid race conditions, add asynchronous fetches to array - let fetchDataPromises = []; + let fetchDataPromises = [] - fetchDataPromises.push(/*getUser(),*/ getTeams()); // <-- Here we must add the function calll to the Financial Beings module. + fetchDataPromises.push(/* getUser(), */ getTeams()) // <-- Here we must add the function calll to the Financial Beings module. // When all asynchronous fetches resolve, authenticate user or throw error. - Promise.all(fetchDataPromises).then(result => { - + Promise.all(fetchDataPromises).then(result => { /* All good, we will go through the results creating a map with all the Images URLs */ - let teamProfileImages = new Map(); - let fbProfileImages = new Map(); + let teamProfileImages = new Map() + let fbProfileImages = new Map() - for (let i = 0; i < teams.edges.length; i++) { + for (let i = 0; i < teams.edges.length; i++) { + let team = teams.edges[i].node - let team = teams.edges[i].node; - - teamProfileImages.set(team.slug, team.profile.avatar); - - if (team.fb.length > 0) { - - fbProfileImages.set(team.slug + "-" + team.fb[0].slug, team.fb[0].avatar); - - } - } - - window.canvasApp.context.teamProfileImages = teamProfileImages; - window.canvasApp.context.fbProfileImages = fbProfileImages; - - callBack(); - - }, err => { - if (ERROR_LOG === true) { logger.write("[ERROR] loadImages -> Error fetching data from Teams Module."); } - if (ERROR_LOG === true) { logger.write("[ERROR] loadImages -> err = " + err); } - }); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] loadImages -> err = " + err); } + teamProfileImages.set(team.slug, team.profile.avatar) + if (team.fb.length > 0) { + fbProfileImages.set(team.slug + '-' + team.fb[0].slug, team.fb[0].avatar) + } } + window.canvasApp.context.teamProfileImages = teamProfileImages + window.canvasApp.context.fbProfileImages = fbProfileImages + + callBack() + }, err => { + if (ERROR_LOG === true) { logger.write('[ERROR] loadImages -> Error fetching data from Teams Module.') } + if (ERROR_LOG === true) { logger.write('[ERROR] loadImages -> err = ' + err) } + }) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] loadImages -> err = ' + err) } } + } } - - diff --git a/Displace.js b/Displace.js index 2a4d8ca1c..328e034c1 100644 --- a/Displace.js +++ b/Displace.js @@ -1,81 +1,64 @@ - -/* +  +/* + +We call displacement to the offset we can produce to the object which the displcement object is is a child from. +The displacement is a vector that displaces everything static drawn on on the context of the parent object. -We call displacement to the offset we can produce to the object which the displcement object is is a child from. -The displacement is a vector that displaces everything static drawn on on the context of the parent object. - */ -function newDisplacement() { +function newDisplacement () { + var displacement = { + containerName: '', // This is for debugging purposes only. + parentDisplacement: undefined, // Here we store the displacement object of the parent cointainer, if exists. + container: undefined, + x: 0, // This is the actual x displacement. + y: 0, // This is the actual y displacement. + displace: displace, + undisplaceThisPoint: undisplaceThisPoint, + displaceThisPoint: displaceThisPoint + } - var displacement = { - containerName: "", // This is for debugging purposes only. - parentDisplacement: undefined, // Here we store the displacement object of the parent cointainer, if exists. - container: undefined, - x: 0, // This is the actual x displacement. - y: 0, // This is the actual y displacement. - displace: displace, - undisplaceThisPoint: undisplaceThisPoint, - displaceThisPoint: displaceThisPoint - }; - - return displacement; - - - function displace(amountX, amountY) { + return displacement + function displace (amountX, amountY) { /* First we check if by allowing this displacement we would produce the current frame to be beyond its limit. */ - tempDisplacement = newDisplacement(); - tempDisplacement.x = amountX; - tempDisplacement.y = amountY; - - if (this.container.frame.canYouMoveHere(tempDisplacement)) { + tempDisplacement = newDisplacement() + tempDisplacement.x = amountX + tempDisplacement.y = amountY + if (this.container.frame.canYouMoveHere(tempDisplacement)) { /* Now we displace */ - displacement.x = displacement.x + amountX; - displacement.y = displacement.y + amountY; + displacement.x = displacement.x + amountX + displacement.y = displacement.y + amountY - return true; - } - - return false; + return true } - function displaceThisPoint(point) { + return false + } - if (this.parentDisplacement !== undefined) { - - point = this.parentDisplacement.displaceThisPoint(point); - - } - - point.x = point.x + displacement.x; - point.y = point.y + displacement.y; - - return point; + function displaceThisPoint (point) { + if (this.parentDisplacement !== undefined) { + point = this.parentDisplacement.displaceThisPoint(point) } - function undisplaceThisPoint(point) { + point.x = point.x + displacement.x + point.y = point.y + displacement.y - if (this.parentDisplacement !== undefined) { + return point + } - point = this.parentDisplacement.undisplaceThisPoint(point); - - } - - point.x = point.x - displacement.x; - point.y = point.y - displacement.y; - - return point; + function undisplaceThisPoint (point) { + if (this.parentDisplacement !== undefined) { + point = this.parentDisplacement.undisplaceThisPoint(point) } + point.x = point.x - displacement.x + point.y = point.y - displacement.y + + return point + } } - - - - - - diff --git a/EventHandler.js b/EventHandler.js index 4e84bee09..9a242b190 100644 --- a/EventHandler.js +++ b/EventHandler.js @@ -1,93 +1,72 @@ - -function newEventHandler() { +  +function newEventHandler () { + const CONSOLE_LOG = false - const CONSOLE_LOG = false; + let thisObject = { + name: undefined, // This is for debugging purposes only. + parentEventHandler: undefined, // Here we store the parent cointainer zoom object. + listenToEvent: listenToEvent, + stopListening: stopListening, + raiseEvent: raiseEvent, + initialize: initialize + } - let thisObject = { - name: undefined, // This is for debugging purposes only. - parentEventHandler: undefined, // Here we store the parent cointainer zoom object. - listenToEvent: listenToEvent, - stopListening: stopListening, - raiseEvent: raiseEvent, - initialize: initialize - }; + var eventHandlers = [] // Here we store all the functions we will call when an event is comming. - var eventHandlers = []; // Here we store all the functions we will call when an event is comming. + return thisObject - return thisObject; + function initialize () { - function initialize() { + } - + function listenToEvent (eventType, handler, extraData) { + eventHandlers.push([eventType, handler, extraData]) + + if (thisObject.name !== undefined && CONSOLE_LOG === true) { + console.log('Event Handler named ' + thisObject.name + ' received a request to listenToEvent ' + eventType + ' and call ' + (handler.toString()).substring(0, 50)) + } + } + + function stopListening (pEventType, pHandler) { + if (thisObject.name !== undefined && CONSOLE_LOG === true) { + console.log('Event Handler named ' + thisObject.name + ' received a request to stop listening to an the event ' + pEventType + ' with this handler: ' + pHandler) } - function listenToEvent(eventType, handler, extraData) { + for (let i = 0; i < eventHandlers.length; i++) { + let record = eventHandlers[i] + let eventType = record[0] + let handler = record[1] - eventHandlers.push([eventType, handler, extraData]); + if (pEventType === eventType && pHandler.toString() === handler.toString()) { + eventHandlers.splice(i, 1) if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to listenToEvent " + eventType + " and call " + (handler.toString()).substring(0, 50)); - + console.log('Evethandler found and deleted.') } + return + } + } + } + + function raiseEvent (eventType, event) { + if (thisObject.name !== undefined && CONSOLE_LOG === true) { + console.log('Event Handler named ' + thisObject.name + ' received a request to raiseEvent ' + eventType + ' with this data ' + (event.toString()).substring(0, 50)) } - function stopListening(pEventType, pHandler) { - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to stop listening to an the event " + pEventType + " with this handler: " + pHandler); - - } - - for (let i = 0; i < eventHandlers.length; i++) { - - let record = eventHandlers[i]; - let eventType = record[0]; - let handler = record[1]; - - if (pEventType === eventType && pHandler.toString() === handler.toString()) { - - eventHandlers.splice(i, 1); - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Evethandler found and deleted."); - - } - - return; - } - } - } - - function raiseEvent(eventType, event) { - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to raiseEvent " + eventType + " with this data " + (event.toString()).substring(0, 50)); - - } - - for (var i = 0; i < eventHandlers.length; i++) { - + for (var i = 0; i < eventHandlers.length; i++) { /* We will execute all the functions listening to this event type. */ - if (eventHandlers[i][0] === eventType) { + if (eventHandlers[i][0] === eventType) { + var handler = eventHandlers[i][1] + var extraData = eventHandlers[i][2] - var handler = eventHandlers[i][1]; - var extraData = eventHandlers[i][2]; - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to raiseEvent " + eventType + " and will call this handler: " + (handler.toString()).substring(0,50)); - - } - - handler(event, extraData); - - } + if (thisObject.name !== undefined && CONSOLE_LOG === true) { + console.log('Event Handler named ' + thisObject.name + ' received a request to raiseEvent ' + eventType + ' and will call this handler: ' + (handler.toString()).substring(0, 50)) } + + handler(event, extraData) + } } + } } diff --git a/Exchange/ExchangeAPI.js b/Exchange/ExchangeAPI.js index 4b2e3c6b2..31dc911f4 100644 --- a/Exchange/ExchangeAPI.js +++ b/Exchange/ExchangeAPI.js @@ -1,166 +1,155 @@ -function newExchangeAPI() { + function newExchangeAPI () { + const INFO_LOG = true + const LOG_FILE_CONTENT = true - const INFO_LOG = true; - const LOG_FILE_CONTENT = true; + const MODULE_NAME = 'CloudVM -> Exchange API' - const MODULE_NAME = "CloudVM -> Exchange API"; + const SERVER_URL = window.canvasApp.urlPrefix + 'ExchangeAPI/' - const SERVER_URL = window.canvasApp.urlPrefix + "ExchangeAPI/"; - - let thisObject = { - initialize: initialize, - getTicker: getTicker, - getOpenPositions: getOpenPositions, - getExecutedTrades: getExecutedTrades, - putPosition: putPosition, - movePosition: movePosition, - getPublicTradeHistory: getPublicTradeHistory - }; + let thisObject = { + initialize: initialize, + getTicker: getTicker, + getOpenPositions: getOpenPositions, + getExecutedTrades: getExecutedTrades, + putPosition: putPosition, + movePosition: movePosition, + getPublicTradeHistory: getPublicTradeHistory + } - return thisObject; - - function initialize(callBackFunction) { + return thisObject + function initialize (callBackFunction) { /* When this initialized is called from the Browser, there is no need to send it to the server since the server will anyways initialize this library at each method call. */ - callBackFunction(window.DEFAULT_OK_RESPONSE); - - } + callBackFunction(window.DEFAULT_OK_RESPONSE) + } - function getTicker(pMarket, callBackFunction) { + function getTicker (pMarket, callBackFunction) { + let authToken = window.localStorage.getItem('access_token') - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + "/" - + "getTicker" + "/" + let path = SERVER_URL + + CURRENT_BOT_CODE_NAME + '/' + + 'getTicker' + '/' + authToken - ; - callServer(undefined, path + "/NO-LOG", onServerResponse); + callServer(undefined, path + '/NO-LOG', onServerResponse) - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } + function onServerResponse (pServerResponse) { + let response = JSON.parse(pServerResponse) + if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } else { + callBackFunction(window.DEFAULT_OK_RESPONSE, response) + } + } + } - function getOpenPositions(pMarket, callBackFunction) { + function getOpenPositions (pMarket, callBackFunction) { + let authToken = window.localStorage.getItem('access_token') - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + "/" - + "getOpenPositions" + "/" + let path = SERVER_URL + + CURRENT_BOT_CODE_NAME + '/' + + 'getOpenPositions' + '/' + authToken - ; - callServer(undefined, path + "/NO-LOG", onServerResponse); + callServer(undefined, path + '/NO-LOG', onServerResponse) - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } + function onServerResponse (pServerResponse) { + let response = JSON.parse(pServerResponse) + if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } else { + callBackFunction(window.DEFAULT_OK_RESPONSE, response) + } + } + } - function getExecutedTrades(pPositionId, callBackFunction) { + function getExecutedTrades (pPositionId, callBackFunction) { + let authToken = window.localStorage.getItem('access_token') - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + "/" - + "getExecutedTrades" + "/" - + authToken + "/" + let path = SERVER_URL + + CURRENT_BOT_CODE_NAME + '/' + + 'getExecutedTrades' + '/' + + authToken + '/' + pPositionId - ; - callServer(undefined, path + "/NO-LOG", onServerResponse); + callServer(undefined, path + '/NO-LOG', onServerResponse) - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } - - function putPosition(pMarket, pType, pRate, pAmountA, pAmountB, callBackFunction) { + function onServerResponse (pServerResponse) { + let response = JSON.parse(pServerResponse) + if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } else { + callBackFunction(window.DEFAULT_OK_RESPONSE, response) + } + } + } - let authToken = window.localStorage.getItem('access_token'); + function putPosition (pMarket, pType, pRate, pAmountA, pAmountB, callBackFunction) { + let authToken = window.localStorage.getItem('access_token') - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + "/" - + "putPosition" + "/" - + authToken + "/" - + pType + "/" - + pRate + "/" - + pAmountA + "/" + let path = SERVER_URL + + CURRENT_BOT_CODE_NAME + '/' + + 'putPosition' + '/' + + authToken + '/' + + pType + '/' + + pRate + '/' + + pAmountA + '/' + pAmountB - ; - callServer(undefined, path + "/NO-LOG", onServerResponse); + callServer(undefined, path + '/NO-LOG', onServerResponse) - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } + function onServerResponse (pServerResponse) { + let response = JSON.parse(pServerResponse) + if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } else { + callBackFunction(window.DEFAULT_OK_RESPONSE, response) + } + } + } - function movePosition(pPositionId, pNewRate, pPositionAmountB, callBackFunction) { + function movePosition (pPositionId, pNewRate, pPositionAmountB, callBackFunction) { + let authToken = window.localStorage.getItem('access_token') - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + "/" - + "movePosition" + "/" - + authToken + "/" - + pPositionId + "/" - + pNewRate + "/" + let path = SERVER_URL + + CURRENT_BOT_CODE_NAME + '/' + + 'movePosition' + '/' + + authToken + '/' + + pPositionId + '/' + + pNewRate + '/' + pPositionAmountB - ; - callServer(undefined, path + "/NO-LOG", onServerResponse); + callServer(undefined, path + '/NO-LOG', onServerResponse) - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } + function onServerResponse (pServerResponse) { + let response = JSON.parse(pServerResponse) + if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } else { + callBackFunction(window.DEFAULT_OK_RESPONSE, response) + } + } + } - function getPublicTradeHistory(pMarket, startTime, endTime, callBackFunction) { + function getPublicTradeHistory (pMarket, startTime, endTime, callBackFunction) { + let authToken = window.localStorage.getItem('access_token') - let authToken = window.localStorage.getItem('access_token'); - - let path = SERVER_URL - + CURRENT_BOT_CODE_NAME + "/" - + "getPublicTradeHistory" + "/" - + authToken + "/" - + startTime + "/" + let path = SERVER_URL + + CURRENT_BOT_CODE_NAME + '/' + + 'getPublicTradeHistory' + '/' + + authToken + '/' + + startTime + '/' + endTime - ; - callServer(undefined, path + "/NO-LOG", onServerResponse); + callServer(undefined, path + '/NO-LOG', onServerResponse) - function onServerResponse(pServerResponse) { - let response = JSON.parse(pServerResponse); - if (response.result === window.DEFAULT_FAIL_RESPONSE.result) - callBackFunction(window.DEFAULT_FAIL_RESPONSE); - else - callBackFunction(window.DEFAULT_OK_RESPONSE, response); - } - } -} + function onServerResponse (pServerResponse) { + let response = JSON.parse(pServerResponse) + if (response.result === window.DEFAULT_FAIL_RESPONSE.result) { + callBackFunction(window.DEFAULT_FAIL_RESPONSE) + } else { callBackFunction(window.DEFAULT_OK_RESPONSE, response) } + } + } + } diff --git a/Files/DailyFiles.js b/Files/DailyFiles.js index c7cbf8314..cf94b1fe2 100644 --- a/Files/DailyFiles.js +++ b/Files/DailyFiles.js @@ -1,392 +1,327 @@ - -function newDailyFiles() { +  +function newDailyFiles () { + const MODULE_NAME = 'Daily Files' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Daily Files"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { + getFileCursor: getFileCursor, + setDatetime: setDatetime, + setTimePeriod: setTimePeriod, + getExpectedFiles: getExpectedFiles, + getFilesLoaded: getFilesLoaded, + initialize: initialize, + finalize: finalize + } - let thisObject = { - getFileCursor: getFileCursor, - setDatetime: setDatetime, - setTimePeriod: setTimePeriod, - getExpectedFiles: getExpectedFiles, - getFilesLoaded: getFilesLoaded, - initialize: initialize, - finalize: finalize + let filesLoaded = 0 + let expectedFiles = 0 + + let fileCloud + + let fileCursors = new Map() + + let callBackWhenFileReceived + + return thisObject + + function finalize () { + try { + if (INFO_LOG === true) { logger.write('[INFO] finalize -> Entering function.') } + + filesLoaded = undefined + expectedFiles = undefined + fileCloud = undefined + + fileCursors.forEach(finalizeEach) + + function finalizeEach (item, key, mapObj) { + if (INFO_LOG === true) { logger.write('[INFO] finalize -> finalizeEach -> Entering function.') } + + item.finalize() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] finalize -> err = ' + err) } } + } - let filesLoaded = 0; - let expectedFiles = 0; + function initialize (pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, pDatetime, pTimePeriod, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - let fileCloud; + callBackWhenFileReceived = callBackFunction - let fileCursors = new Map; + let exchange = ecosystem.getExchange(pProduct, pExchange) - let callBackWhenFileReceived; + if (exchange === undefined) { + throw 'Exchange not supoorted by this product of the ecosystem! - pDevTeam.codeName = ' + pDevTeam.codeName + ', pBot.codeName = ' + pBot.codeName + ', pProduct.codeName = ' + pProduct.codeName + ', pExchange = ' + pExchange + } - return thisObject; - - function finalize() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] finalize -> Entering function."); } - - filesLoaded = undefined; - expectedFiles = undefined; - fileCloud = undefined; - - fileCursors.forEach(finalizeEach); - - function finalizeEach(item, key, mapObj) { - - if (INFO_LOG === true) { logger.write("[INFO] finalize -> finalizeEach -> Entering function."); } - - item.finalize(); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] finalize -> err = " + err); } - } - } - - function initialize(pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, pDatetime, pTimePeriod, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - callBackWhenFileReceived = callBackFunction; - - let exchange = ecosystem.getExchange(pProduct, pExchange); - - if (exchange === undefined) { - - throw "Exchange not supoorted by this product of the ecosystem! - pDevTeam.codeName = " + pDevTeam.codeName + ", pBot.codeName = " + pBot.codeName + ", pProduct.codeName = " + pProduct.codeName + ", pExchange = " + pExchange; - - } - - fileCloud = newFileCloud(); - fileCloud.initialize(pBot); + fileCloud = newFileCloud() + fileCloud.initialize(pBot) /* First we will get the Data Range */ - fileCloud.getFile(pDevTeam, pBot, pSet, exchange, pMarket, undefined, undefined, undefined, true, onDataRangeReceived); + fileCloud.getFile(pDevTeam, pBot, pSet, exchange, pMarket, undefined, undefined, undefined, true, onDataRangeReceived) - function onDataRangeReceived(err, pFile) { + function onDataRangeReceived (err, pFile) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Entering function.') } - try { + let beginDateRange + let endDateRange - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Entering function."); } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received OK Response.') } - let beginDateRange; - let endDateRange; + beginDateRange = new Date(pFile.begin) + endDateRange = new Date(pFile.end) - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + break + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received OK Response."); } + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - beginDateRange = new Date(pFile.begin); - endDateRange = new Date(pFile.end); + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> err.message = ' + err.message) } - break; - } + if (err.message === 'File does not exist.') { + if (INFO_LOG === true) { logger.write('[WARN] initialize -> onFileReceived -> No Date Range file found. maxDate will be set to current datetime. ') } - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + endDateRange = new Date() + break + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } + if (err.message === 'Missing Configuration.') { + if (ERROR_LOG === true) { logger.write('[WARN] initialize -> onFileReceived -> The needed configuration for the dateRange at the dataSet of the product was not found.') } + if (ERROR_LOG === true) { logger.write('[WARN] initialize -> onFileReceived -> maxDate will be set to current datetime.') } - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> err.message = " + err.message); } - - if (err.message === "File does not exist.") { - - if (INFO_LOG === true) { logger.write("[WARN] initialize -> onFileReceived -> No Date Range file found. maxDate will be set to current datetime. "); } - - endDateRange = new Date(); - break; - } - - if (err.message === "Missing Configuration.") { - - if (ERROR_LOG === true) { logger.write("[WARN] initialize -> onFileReceived -> The needed configuration for the dateRange at the dataSet of the product was not found."); } - if (ERROR_LOG === true) { logger.write("[WARN] initialize -> onFileReceived -> maxDate will be set to current datetime."); } - - endDateRange = new Date(); - break; - } + endDateRange = new Date() + break + } /* If none of the previous conditions are met, the we return the err to the caller. */ - callBackFunction(err); - return; - } + callBackFunction(err) + return + } - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } /* Now we will get the daily files */ - for (i = 0; i < dailyFilePeriods.length; i++) { + for (i = 0; i < dailyFilePeriods.length; i++) { + let periodTime = dailyFilePeriods[i][0] + let periodName = dailyFilePeriods[i][1] - let periodTime = dailyFilePeriods[i][0]; - let periodName = dailyFilePeriods[i][1]; + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> periodTime = ' + periodTime) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> periodName = ' + periodName) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> periodTime = " + periodTime); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> periodName = " + periodName); } + if (pSet.validPeriods.includes(periodName) === true) { + let fileCursor = newFileCursor() + fileCursor.initialize(fileCloud, pDevTeam, pBot, pSet, exchange, pMarket, periodName, periodTime, pDatetime, pTimePeriod, beginDateRange, endDateRange, onInitialized) - if (pSet.validPeriods.includes(periodName) === true) { + function onInitialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> onInitialized -> Entering function.') } - let fileCursor = newFileCursor(); - fileCursor.initialize(fileCloud, pDevTeam, pBot, pSet, exchange, pMarket, periodName, periodTime, pDatetime, pTimePeriod, beginDateRange, endDateRange, onInitialized); + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { - function onInitialized(err) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> onInitialized -> Received OK Response.') } + break + } - try { + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> onInitialized -> Entering function."); } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> onInitialized -> Received FAIL Response.') } + callBackWhenFileReceived(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + default: { - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> onInitialized -> Received Unexpected Response.') } + callBackWhenFileReceived(err) + return + } + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> onInitialized -> Received OK Response."); } - break; - } + fileCursors.set(periodTime, fileCursor) - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> onInitialized -> expectedFiles = ' + expectedFiles) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> onInitialized -> Received FAIL Response."); } - callBackWhenFileReceived(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> onInitialized -> Received Unexpected Response."); } - callBackWhenFileReceived(err); - return; - } - } - - fileCursors.set(periodTime, fileCursor); - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> onInitialized -> expectedFiles = " + expectedFiles); } - - expectedFiles = expectedFiles + fileCursor.getExpectedFiles(); - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> onInitialized -> expectedFiles = " + expectedFiles); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileReceived -> onInitialized -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - } - } - - loadThemAll(); - - function loadThemAll() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> loadThemAll -> Entering function."); } - - for (i = 0; i < dailyFilePeriods.length; i++) { - - let periodTime = dailyFilePeriods[i][0]; - let periodName = dailyFilePeriods[i][1]; - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> loadThemAll -> periodTime = " + periodTime); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> loadThemAll -> periodName = " + periodName); } - - if (pSet.validPeriods.includes(periodName) === true) { - - let fileCursor = fileCursors.get(periodTime); - fileCursor.reload(onFileReceived); - - } - } - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileReceived -> loadThemAll -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } + expectedFiles = expectedFiles + fileCursor.getExpectedFiles() + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> onInitialized -> expectedFiles = ' + expectedFiles) } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileReceived -> onInitialized -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } } + } - } catch (err) { + loadThemAll() - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } + function loadThemAll () { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> loadThemAll -> Entering function.') } - function onFileReceived(err) { + for (i = 0; i < dailyFilePeriods.length; i++) { + let periodTime = dailyFilePeriods[i][0] + let periodName = dailyFilePeriods[i][1] - try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> loadThemAll -> periodTime = ' + periodTime) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> loadThemAll -> periodName = ' + periodName) } - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> Received FAIL Response."); } - callBackWhenFileReceived(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> err.message = " + err.message); } - - callBackWhenFileReceived(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> Received Unexpected Response."); } - callBackWhenFileReceived(err); - return; + if (pSet.validPeriods.includes(periodName) === true) { + let fileCursor = fileCursors.get(periodTime) + fileCursor.reload(onFileReceived) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileReceived -> loadThemAll -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } - - filesLoaded++; - - if (INFO_LOG === true) { logger.write("[INFO] onFileReceived -> filesLoaded = " + filesLoaded); } - - callBackWhenFileReceived(GLOBAL.DEFAULT_OK_RESPONSE, thisObject); // Note that the call back is called for every file loaded at each cursor. - + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] onFileReceived -> err = " + err); } - callBackWhenFileReceived(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function getFileCursor(pPeriod) { + function onFileReceived (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] getFileCursor -> Entering function."); } - - return fileCursors.get(pPeriod); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFileCursor -> err = " + err); } - + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> Received OK Response.') } + break } - } - function setDatetime(pDatetime) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> Entering function."); } - - filesLoaded = 0; - expectedFiles = 0; - - fileCursors.forEach(setDatetimeToEach) - - function setDatetimeToEach(fileCursor, key, map) { - - fileCursor.setDatetime(pDatetime); - - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> expectedFiles = " + expectedFiles); } - - expectedFiles = expectedFiles + fileCursor.getExpectedFiles(); - - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> expectedFiles = " + expectedFiles); } - - fileCursor.reload(onFileReceived); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setDatetime -> err = " + err); } - + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> Received FAIL Response.') } + callBackWhenFileReceived(GLOBAL.DEFAULT_FAIL_RESPONSE) + return } - } - function setTimePeriod(pTimePeriod, pDatetime) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> Entering function."); } - - filesLoaded = 0; - expectedFiles = 0; - - fileCursors.forEach(setTimePeriodToEach) - - function setTimePeriodToEach(fileCursor, key, map) { - - fileCursor.setTimePeriod(pTimePeriod, pDatetime); - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> expectedFiles = " + expectedFiles); } - - expectedFiles = expectedFiles + fileCursor.getExpectedFiles(); - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> expectedFiles = " + expectedFiles); } - - fileCursor.reload(onFileReceived); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setTimePeriod -> err = " + err); } + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> err.message = ' + err.message) } + callBackWhenFileReceived(err) + return } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> Received Unexpected Response.') } + callBackWhenFileReceived(err) + return + } + } + + filesLoaded++ + + if (INFO_LOG === true) { logger.write('[INFO] onFileReceived -> filesLoaded = ' + filesLoaded) } + + callBackWhenFileReceived(GLOBAL.DEFAULT_OK_RESPONSE, thisObject) // Note that the call back is called for every file loaded at each cursor. + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] onFileReceived -> err = ' + err) } + callBackWhenFileReceived(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function getExpectedFiles() { - - if (INFO_LOG === true) { logger.write("[INFO] getExpectedFiles -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] getExpectedFiles -> expectedFiles = " + expectedFiles); } - - return expectedFiles; + function getFileCursor (pPeriod) { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFileCursor -> Entering function.') } + return fileCursors.get(pPeriod) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getFileCursor -> err = ' + err) } } + } - function getFilesLoaded() { + function setDatetime (pDatetime) { + try { + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getFilesLoaded -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] getFilesLoaded -> filesLoaded = " + filesLoaded); } + filesLoaded = 0 + expectedFiles = 0 - return filesLoaded; + fileCursors.forEach(setDatetimeToEach) + function setDatetimeToEach (fileCursor, key, map) { + fileCursor.setDatetime(pDatetime) + + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> expectedFiles = ' + expectedFiles) } + + expectedFiles = expectedFiles + fileCursor.getExpectedFiles() + + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> expectedFiles = ' + expectedFiles) } + + fileCursor.reload(onFileReceived) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] setDatetime -> err = ' + err) } } -} \ No newline at end of file + } + + function setTimePeriod (pTimePeriod, pDatetime) { + try { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> Entering function.') } + + filesLoaded = 0 + expectedFiles = 0 + + fileCursors.forEach(setTimePeriodToEach) + + function setTimePeriodToEach (fileCursor, key, map) { + fileCursor.setTimePeriod(pTimePeriod, pDatetime) + + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> expectedFiles = ' + expectedFiles) } + + expectedFiles = expectedFiles + fileCursor.getExpectedFiles() + + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> expectedFiles = ' + expectedFiles) } + + fileCursor.reload(onFileReceived) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] setTimePeriod -> err = ' + err) } + } + } + + function getExpectedFiles () { + if (INFO_LOG === true) { logger.write('[INFO] getExpectedFiles -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] getExpectedFiles -> expectedFiles = ' + expectedFiles) } + + return expectedFiles + } + + function getFilesLoaded () { + if (INFO_LOG === true) { logger.write('[INFO] getFilesLoaded -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] getFilesLoaded -> filesLoaded = ' + filesLoaded) } + + return filesLoaded + } +} diff --git a/Files/FileCloud.js b/Files/FileCloud.js index 4173eb528..8d0964413 100644 --- a/Files/FileCloud.js +++ b/Files/FileCloud.js @@ -1,252 +1,210 @@ - -function newFileCloud() { - - const MODULE_NAME = "File Cloud"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; +  +function newFileCloud () { + const MODULE_NAME = 'File Cloud' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME /* - This is the module in the system that actually connects to the cloud storage and grabs from there the needed files. + This is the module in the system that actually connects to the cloud storage and grabs from there the needed files. */ - var thisObject = { - getFile: getFile, - initialize: initialize - }; + var thisObject = { + getFile: getFile, + initialize: initialize + } - let blobService; + let blobService - return thisObject; + return thisObject - function initialize(pBot) { + function initialize (pBot) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> pBot = ' + pBot.codeName) } - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> pBot = " + pBot.codeName); } - - blobService = AzureStorage.Blob.createBlobServiceWithSas(pBot.storage.fileUri, pBot.storage.sas); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - //callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); TODO> Handle this callback. - } + blobService = AzureStorage.Blob.createBlobServiceWithSas(pBot.storage.fileUri, pBot.storage.sas) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + // callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); TODO> Handle this callback. } + } - function getFile(pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) { + function getFile (pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFile -> Entering function.') } + const MAX_RETRIES = 3 + + getFileRecursively(0, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) + + function getFileRecursively (pRetryCounter, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) { try { - - if (INFO_LOG === true) { logger.write("[INFO] getFile -> Entering function."); } - - const MAX_RETRIES = 3; - - getFileRecursively(0, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) - - function getFileRecursively(pRetryCounter, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pSet.filePath + "-" + pSet.fileName); } - - let fileName; - let filePath; - - if (pDataRange === undefined) { - - fileName = pSet.fileName; - filePath = pSet.filePath; - - } else { - - if (pSet.dataRange !== undefined) { - - fileName = pSet.dataRange.fileName; - filePath = pSet.dataRange.filePath; - - } else { - - let customErr = { - result: GLOBAL.CUSTOM_FAIL_RESPONSE.result, - message: "Missing Configuration." - }; - - if (ERROR_LOG === true) { logger.write("[WARN] getFile -> getFileRecursively -> onFileReceived -> customErr.message = " + customErr.message); } - if (ERROR_LOG === true) { logger.write("[WARN] getFile -> getFileRecursively -> onFileReceived -> Data Range configuration could not be found. "); } - - callBackFunction(customErr); - return; - } - } - - if (fileName === undefined) { - - logger.write("[ERROR] getFile -> getFileRecursively -> Inconsistant data. Check the following: "); - logger.write("[ERROR] getFile -> getFileRecursively -> pDevTeam = " + JSON.stringify(pDevTeam)); - logger.write("[ERROR] getFile -> getFileRecursively -> pBot = " + JSON.stringify(pBot)); - logger.write("[ERROR] getFile -> getFileRecursively -> pSet = " + JSON.stringify(pSet)); - logger.write("[ERROR] getFile -> getFileRecursively -> pExchange = " + JSON.stringify(pExchange)); - logger.write("[ERROR] getFile -> getFileRecursively -> pMarket = " + JSON.stringify(pMarket)); - logger.write("[ERROR] getFile -> getFileRecursively -> pPeriodName = " + JSON.stringify(pPeriodName)); - - throw ("Inconsistant data received."); - } - - if (pMarket !== undefined) { - - fileName = fileName.replace("@AssetA", pMarket.assetA); - fileName = fileName.replace("@AssetB", pMarket.assetB); - } - - if (pDevTeam !== undefined) { - - filePath = filePath.replace("@DevTeam", pDevTeam.codeName); - } - - if (pBot !== undefined) { - - filePath = filePath.replace("@Bot", pBot.codeName); - } - - if (pExchange !== undefined) { - - filePath = filePath.replace("@Exchange", pExchange.name); - } - - filePath = filePath.replace("@Period", pPeriodName); - - if (pDatetime !== undefined) { - - filePath = filePath.replace("@Year", pDatetime.getUTCFullYear()); - filePath = filePath.replace("@Month", pad(pDatetime.getUTCMonth() + 1, 2)); - filePath = filePath.replace("@Day", pad(pDatetime.getUTCDate(), 2)); - filePath = filePath.replace("@Hour", pad(pDatetime.getUTCHours(), 2)); - filePath = filePath.replace("@Minute", pad(pDatetime.getUTCMinutes(), 2)); - - } - - if (pSequence !== undefined) { - - fileName = fileName.replace("@Sequence", pSequence); - } - - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> filePath = " + filePath); } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> fileName = " + fileName); } - - let containerName; - - containerName = pDevTeam.codeName.toLowerCase(); - - blobService.getBlobToText(containerName, filePath + "/" + fileName, onFileReceived); - - function onFileReceived(err, text, response) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> onFileReceived -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> onFileReceived -> filePath = " + filePath); } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> onFileReceived -> fileName = " + fileName); } - - let data; - - if (err) { - - if (err.code === "BlobNotFound" | err.code === "FileNotFound" | err.code === "ParentNotFound") { - - let customErr = { - result: GLOBAL.CUSTOM_FAIL_RESPONSE.result, - message: "File does not exist." - }; - - if (INFO_LOG === true) { logger.write("[WARN] getFile -> getFileRecursively -> onFileReceived -> customErr.message = " + customErr.message); } - - callBackFunction(customErr); - return; - } - - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> containerName = " + containerName); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> filePath = " + filePath); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> fileName = " + fileName); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> Unexpected Error Ocurred."); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> err = " + err); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> text = " + text); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> response = " + response); } - - if (err.message === "XHR error") { - - if (pRetryCounter < MAX_RETRIES) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> Retrying to get this file. "); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> MAX_RETRIES = " + MAX_RETRIES); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> pRetryCounter = " + pRetryCounter); } - - getFileRecursively(pRetryCounter + 1, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) - return; - - } else { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> Could not get this file from storage. "); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> MAX_RETRIES = " + MAX_RETRIES); } - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> pRetryCounter = " + pRetryCounter); } - - } - } - - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - - } else { - - try { - - data = JSON.parse(text); - - if (INFO_LOG === true) { logger.write("[INFO] getFile -> getFileRecursively -> onFileReceived -> Data received is valid JSON."); } - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE, data); - return; - - } catch (err) { - - if (INFO_LOG === true) { logger.write("[WARN] getFile -> getFileRecursively -> onFileReceived -> err = " + err); } - - let customErr = { - result: GLOBAL.CUSTOM_OK_RESPONSE.result, - message: "Data not in JSON Format." - }; - - if (INFO_LOG === true) { logger.write("[WARN] getFile -> getFileRecursively -> onFileReceived -> customErr.message = " + customErr.message); } - - callBackFunction(customErr, text); - return; - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> getFileRecursively -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pSet.filePath + '-' + pSet.fileName) } + + let fileName + let filePath + + if (pDataRange === undefined) { + fileName = pSet.fileName + filePath = pSet.filePath + } else { + if (pSet.dataRange !== undefined) { + fileName = pSet.dataRange.fileName + filePath = pSet.dataRange.filePath + } else { + let customErr = { + result: GLOBAL.CUSTOM_FAIL_RESPONSE.result, + message: 'Missing Configuration.' + } + + if (ERROR_LOG === true) { logger.write('[WARN] getFile -> getFileRecursively -> onFileReceived -> customErr.message = ' + customErr.message) } + if (ERROR_LOG === true) { logger.write('[WARN] getFile -> getFileRecursively -> onFileReceived -> Data Range configuration could not be found. ') } + + callBackFunction(customErr) + return } + } + if (fileName === undefined) { + logger.write('[ERROR] getFile -> getFileRecursively -> Inconsistant data. Check the following: ') + logger.write('[ERROR] getFile -> getFileRecursively -> pDevTeam = ' + JSON.stringify(pDevTeam)) + logger.write('[ERROR] getFile -> getFileRecursively -> pBot = ' + JSON.stringify(pBot)) + logger.write('[ERROR] getFile -> getFileRecursively -> pSet = ' + JSON.stringify(pSet)) + logger.write('[ERROR] getFile -> getFileRecursively -> pExchange = ' + JSON.stringify(pExchange)) + logger.write('[ERROR] getFile -> getFileRecursively -> pMarket = ' + JSON.stringify(pMarket)) + logger.write('[ERROR] getFile -> getFileRecursively -> pPeriodName = ' + JSON.stringify(pPeriodName)) + throw ('Inconsistant data received.') + } + + if (pMarket !== undefined) { + fileName = fileName.replace('@AssetA', pMarket.assetA) + fileName = fileName.replace('@AssetB', pMarket.assetB) + } + + if (pDevTeam !== undefined) { + filePath = filePath.replace('@DevTeam', pDevTeam.codeName) + } + + if (pBot !== undefined) { + filePath = filePath.replace('@Bot', pBot.codeName) + } + + if (pExchange !== undefined) { + filePath = filePath.replace('@Exchange', pExchange.name) + } + + filePath = filePath.replace('@Period', pPeriodName) + + if (pDatetime !== undefined) { + filePath = filePath.replace('@Year', pDatetime.getUTCFullYear()) + filePath = filePath.replace('@Month', pad(pDatetime.getUTCMonth() + 1, 2)) + filePath = filePath.replace('@Day', pad(pDatetime.getUTCDate(), 2)) + filePath = filePath.replace('@Hour', pad(pDatetime.getUTCHours(), 2)) + filePath = filePath.replace('@Minute', pad(pDatetime.getUTCMinutes(), 2)) + } + + if (pSequence !== undefined) { + fileName = fileName.replace('@Sequence', pSequence) + } + + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> filePath = ' + filePath) } + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> fileName = ' + fileName) } + + let containerName + + containerName = pDevTeam.codeName.toLowerCase() + + blobService.getBlobToText(containerName, filePath + '/' + fileName, onFileReceived) + + function onFileReceived (err, text, response) { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> onFileReceived -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> onFileReceived -> filePath = ' + filePath) } + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> onFileReceived -> fileName = ' + fileName) } + + let data + + if (err) { + if (err.code === 'BlobNotFound' | err.code === 'FileNotFound' | err.code === 'ParentNotFound') { + let customErr = { + result: GLOBAL.CUSTOM_FAIL_RESPONSE.result, + message: 'File does not exist.' + } + + if (INFO_LOG === true) { logger.write('[WARN] getFile -> getFileRecursively -> onFileReceived -> customErr.message = ' + customErr.message) } + + callBackFunction(customErr) + return + } + + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> containerName = ' + containerName) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> filePath = ' + filePath) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> fileName = ' + fileName) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> Unexpected Error Ocurred.') } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> err = ' + err) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> text = ' + text) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> response = ' + response) } + + if (err.message === 'XHR error') { + if (pRetryCounter < MAX_RETRIES) { + + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> Retrying to get this file. ') } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> MAX_RETRIES = ' + MAX_RETRIES) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> pRetryCounter = ' + pRetryCounter) } + + getFileRecursively(pRetryCounter + 1, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pDatetime, pSequence, pDataRange, callBackFunction) + return + } else { + + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> Could not get this file from storage. ') } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> MAX_RETRIES = ' + MAX_RETRIES) } + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> pRetryCounter = ' + pRetryCounter) } + } + } + + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } else { + try { + data = JSON.parse(text) + + if (INFO_LOG === true) { logger.write('[INFO] getFile -> getFileRecursively -> onFileReceived -> Data received is valid JSON.') } + + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE, data) + return + } catch (err) { + if (INFO_LOG === true) { logger.write('[WARN] getFile -> getFileRecursively -> onFileReceived -> err = ' + err) } + + let customErr = { + result: GLOBAL.CUSTOM_OK_RESPONSE.result, + message: 'Data not in JSON Format.' + } + + if (INFO_LOG === true) { logger.write('[WARN] getFile -> getFileRecursively -> onFileReceived -> customErr.message = ' + customErr.message) } + + callBackFunction(customErr, text) + return + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFile -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> getFileRecursively -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getFile -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } -} \ No newline at end of file + } +} diff --git a/Files/FileCursor.js b/Files/FileCursor.js index 9592c2c1f..755cacc03 100644 --- a/Files/FileCursor.js +++ b/Files/FileCursor.js @@ -1,688 +1,586 @@ - -function newFileCursor() { +  +function newFileCursor () { + const MODULE_NAME = 'File Cursor' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "File Cursor"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let cursorDate - let cursorDate; + let thisObject = { + reload: reload, + setDatetime: setDatetime, + setTimePeriod: setTimePeriod, + files: new Map(), + getExpectedFiles: getExpectedFiles, + initialize: initialize, + finalize: finalize + } - let thisObject = { - reload: reload, - setDatetime: setDatetime, - setTimePeriod: setTimePeriod, - files: new Map, - getExpectedFiles: getExpectedFiles, - initialize: initialize, - finalize: finalize - }; + let minCursorSize = 10 + let maxCursorSize = 30 - let minCursorSize = 10; - let maxCursorSize = 30; + let market + let exchange + let fileCloud + let devTeam + let bot + let thisSet + let periodName + let timePeriod + let beginDateRange + let endDateRange - let market; - let exchange; - let fileCloud; - let devTeam; - let bot; - let thisSet; - let periodName; - let timePeriod; - let beginDateRange; - let endDateRange; + let intervalHandle - let intervalHandle; + return thisObject - return thisObject; + function finalize () { + try { + if (INFO_LOG === true) { logger.write('[INFO] finalize -> Entering function.') } - function finalize() { + clearInterval(intervalHandle) - try { - - if (INFO_LOG === true) { logger.write("[INFO] finalize -> Entering function."); } - - clearInterval(intervalHandle); - - thisObject.files = undefined; - cursorDate = undefined; - fileCloud = undefined; - periodName = undefined; - timePeriod = undefined; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] finalize -> err = " + err); } - } + thisObject.files = undefined + cursorDate = undefined + fileCloud = undefined + periodName = undefined + timePeriod = undefined + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] finalize -> err = ' + err) } } + } - function initialize(pFileCloud, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pTimePeriod, pCursorDate, pCurrentTimePeriod, pBeginDateRange, pEndDateRange, callBackFunction) { + function initialize (pFileCloud, pDevTeam, pBot, pSet, pExchange, pMarket, pPeriodName, pTimePeriod, pCursorDate, pCurrentTimePeriod, pBeginDateRange, pEndDateRange, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pSet.codeName + '-' + pPeriodName) } - try { + market = pMarket + exchange = pExchange + fileCloud = pFileCloud + devTeam = pDevTeam + bot = pBot + thisSet = pSet + periodName = pPeriodName + cursorDate = pCursorDate + timePeriod = pTimePeriod + beginDateRange = pBeginDateRange + endDateRange = pEndDateRange - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pSet.codeName + "-" + pPeriodName); } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> market = ' + market) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> periodName = ' + periodName) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> cursorDate = ' + cursorDate) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> beginDateRange = ' + beginDateRange) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> endDateRange = ' + endDateRange) } - market = pMarket; - exchange = pExchange; - fileCloud = pFileCloud; - devTeam = pDevTeam; - bot = pBot; - thisSet = pSet; - periodName = pPeriodName; - cursorDate = pCursorDate; - timePeriod = pTimePeriod; - beginDateRange = pBeginDateRange; - endDateRange = pEndDateRange; + setTimePeriod(pCurrentTimePeriod, pCursorDate) - if (INFO_LOG === true) { logger.write("[INFO] initialize -> market = " + market); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> periodName = " + periodName); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> cursorDate = " + cursorDate); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> beginDateRange = " + beginDateRange); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> endDateRange = " + endDateRange); } + intervalHandle = setInterval(updateFiles, timePeriod) - setTimePeriod(pCurrentTimePeriod, pCursorDate); - - intervalHandle = setInterval(updateFiles , timePeriod); - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function updateFiles() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> Entering function."); } + function updateFiles () { + try { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> Entering function.') } /* In order to know if we need to update any file we follow this logic: 1. If the current date is already a file in the cursor, we need to update it. - 2. If the current date is one day ahead of a file in the cursor, we need to add this one to the cursor. + 2. If the current date is one day ahead of a file in the cursor, we need to add this one to the cursor. */ - let targetDate; - let dateString; - let file; + let targetDate + let dateString + let file /* Situation 1 */ - targetDate = new Date(); - dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2); + targetDate = new Date() + dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2) - file = thisObject.files.get(dateString); + file = thisObject.files.get(dateString) - if (file !== undefined) { + if (file !== undefined) { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> File found at the cursor, proceeding to update.') } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> File found at the cursor, proceeding to update."); } + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, targetDate, undefined, undefined, onFileReceived) - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, targetDate, undefined, undefined, onFileReceived); - - return; - } + return + } /* Situation 2 */ - targetDate = new Date( (new Date()).valueOf() - ONE_DAY_IN_MILISECONDS); - dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2); + targetDate = new Date((new Date()).valueOf() - ONE_DAY_IN_MILISECONDS) + dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2) - file = thisObject.files.get(dateString); // This is from yesterday + file = thisObject.files.get(dateString) // This is from yesterday - targetDate = new Date(); - dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2); + targetDate = new Date() + dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2) - if (file !== undefined) { + if (file !== undefined) { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> Previous day file found at the cursor, proceeding to add current date.') } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> Previous day file found at the cursor, proceeding to add current date."); } + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, targetDate, undefined, undefined, onFileReceived) - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, targetDate, undefined, undefined, onFileReceived); - - return; - } - - function onFileReceived(err, file) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received FAIL Response."); } - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received Unexpected Response."); } - return; - } - } - - thisObject.files.set(dateString, file); - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> File updated."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> devTeam = " + devTeam.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> bot = " + bot.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> thisSet = " + thisSet.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> dateString = " + dateString); } - - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> err = " + err); } - } - } - - function setTimePeriod(pTimePeriod, pDatetime) { + return + } + function onFileReceived (err, file) { try { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> Entering function."); } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received OK Response.') } + break + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received FAIL Response.') } + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received Unexpected Response.') } + return + } + } + + thisObject.files.set(dateString, file) + + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> File updated.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> devTeam = ' + devTeam.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> bot = ' + bot.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> thisSet = ' + thisSet.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> dateString = ' + dateString) } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> err = ' + err) } + } + } + + function setTimePeriod (pTimePeriod, pDatetime) { + try { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> Entering function.') } /* - + We are implementing here an algorithm designed to save bandwidth, memory and processing power at the browser. We say there is a saving mode where the cursor is running at a minimum size. When the end user aproaches the time period the cursor is set, then it should exit the saving mode and go to its actual size. - + To do this we are going to measure the distance from the Time Period received to the one the cursors was initialized with. If these periods are consecutive, it means that the cursor should exit saving mode and load its full size. - + */ - cursorDate = pDatetime; // Adjust the cursor date to the one received. + cursorDate = pDatetime // Adjust the cursor date to the one received. - let positionA; + let positionA - for (let i = 0; i < dailyFilePeriods.length; i++) { + for (let i = 0; i < dailyFilePeriods.length; i++) { + let period = dailyFilePeriods[i] - let period = dailyFilePeriods[i]; - - if (period[0] === pTimePeriod) { - - positionA = i; - - } - - if (period[0] === timePeriod) { - - positionB = i; - - } - } - - if (Math.abs(positionB - positionA) <= 1) { - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> Will EXIT Saving Mode."); } - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> pTimePeriod = " + convertTimePeriodToName(pTimePeriod)); } - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> timePeriod = " + convertTimePeriodToName(timePeriod)); } - - exitSavingMode(); - - } else { - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> Will ENTER Saving Mode."); } - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> pTimePeriod = " + convertTimePeriodToName(pTimePeriod)); } - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> timePeriod = " + convertTimePeriodToName(timePeriod)); } - - enterSavingMode(); - - } - - function enterSavingMode() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> enterSavingMode -> Entering function."); } - - switch (timePeriod) { - - case _45_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 30; - } - break; - case _40_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 20; - } - break; - case _30_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _20_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _15_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _10_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _5_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _4_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _3_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _2_MINUTES_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - case _1_MINUTE_IN_MILISECONDS: - { - minCursorSize = 3; - maxCursorSize = 15; - } - break; - default: - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setTimePeriod -> enterSavingMode -> err = " + err); } - } - } - - function exitSavingMode() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> exitSavingMode -> Entering function."); } - - switch (timePeriod) { - - case _45_MINUTES_IN_MILISECONDS: - { - minCursorSize = 15; - maxCursorSize = 30; - } - break; - case _40_MINUTES_IN_MILISECONDS: - { - minCursorSize = 13; - maxCursorSize = 20; - } - break; - case _30_MINUTES_IN_MILISECONDS: - { - minCursorSize = 11; - maxCursorSize = 15; - } - break; - case _20_MINUTES_IN_MILISECONDS: - { - minCursorSize = 9; - maxCursorSize = 15; - } - break; - case _15_MINUTES_IN_MILISECONDS: - { - minCursorSize = 7; - maxCursorSize = 15; - } - break; - case _10_MINUTES_IN_MILISECONDS: - { - minCursorSize = 7; - maxCursorSize = 15; - } - break; - case _5_MINUTES_IN_MILISECONDS: - { - minCursorSize = 5; - maxCursorSize = 15; - } - break; - case _4_MINUTES_IN_MILISECONDS: - { - minCursorSize = 5; - maxCursorSize = 15; - } - break; - case _3_MINUTES_IN_MILISECONDS: - { - minCursorSize = 5; - maxCursorSize = 15; - } - break; - case _2_MINUTES_IN_MILISECONDS: - { - minCursorSize = 5; - maxCursorSize = 15; - } - break; - case _1_MINUTE_IN_MILISECONDS: - { - minCursorSize = 5; - maxCursorSize = 15; - } - break; - default: - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setTimePeriod -> exitSavingMode -> err = " + err); } - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setTimePeriod -> err = " + err); } + if (period[0] === pTimePeriod) { + positionA = i } - } - function setDatetime(pDatetime) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> Entering function."); } - - if (pDatetime === undefined) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setDatetime -> Received undefined datetime."); } - return; - } - - cursorDate = pDatetime; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] setDatetime -> err = " + err); } + if (period[0] === timePeriod) { + positionB = i } - } + } - function reload(callBackFunction) { + if (Math.abs(positionB - positionA) <= 1) { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> Will EXIT Saving Mode.') } + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> pTimePeriod = ' + convertTimePeriodToName(pTimePeriod)) } + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> timePeriod = ' + convertTimePeriodToName(timePeriod)) } + exitSavingMode() + } else { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> Will ENTER Saving Mode.') } + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> pTimePeriod = ' + convertTimePeriodToName(pTimePeriod)) } + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> timePeriod = ' + convertTimePeriodToName(timePeriod)) } + + enterSavingMode() + } + + function enterSavingMode () { try { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> enterSavingMode -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] reload -> Entering function."); } - - getFiles(callBackFunction); - - collectGarbage(callBackFunction); + switch (timePeriod) { + case _45_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 30 + } + break + case _40_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 20 + } + break + case _30_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _20_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _15_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _10_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _5_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _4_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _3_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _2_MINUTES_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + case _1_MINUTE_IN_MILISECONDS: + { + minCursorSize = 3 + maxCursorSize = 15 + } + break + default: + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] reload -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] setTimePeriod -> enterSavingMode -> err = ' + err) } } - } - - function getFiles(callBackFunction) { + } + function exitSavingMode () { try { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> exitSavingMode -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> Entering function."); } + switch (timePeriod) { - let i = 0; - let j = 0; + case _45_MINUTES_IN_MILISECONDS: + { + minCursorSize = 15 + maxCursorSize = 30 + } + break + case _40_MINUTES_IN_MILISECONDS: + { + minCursorSize = 13 + maxCursorSize = 20 + } + break + case _30_MINUTES_IN_MILISECONDS: + { + minCursorSize = 11 + maxCursorSize = 15 + } + break + case _20_MINUTES_IN_MILISECONDS: + { + minCursorSize = 9 + maxCursorSize = 15 + } + break + case _15_MINUTES_IN_MILISECONDS: + { + minCursorSize = 7 + maxCursorSize = 15 + } + break + case _10_MINUTES_IN_MILISECONDS: + { + minCursorSize = 7 + maxCursorSize = 15 + } + break + case _5_MINUTES_IN_MILISECONDS: + { + minCursorSize = 5 + maxCursorSize = 15 + } + break + case _4_MINUTES_IN_MILISECONDS: + { + minCursorSize = 5 + maxCursorSize = 15 + } + break + case _3_MINUTES_IN_MILISECONDS: + { + minCursorSize = 5 + maxCursorSize = 15 + } + break + case _2_MINUTES_IN_MILISECONDS: + { + minCursorSize = 5 + maxCursorSize = 15 + } + break + case _1_MINUTE_IN_MILISECONDS: + { + minCursorSize = 5 + maxCursorSize = 15 + } + break + default: + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] setTimePeriod -> exitSavingMode -> err = ' + err) } + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] setTimePeriod -> err = ' + err) } + } + } - let dateString; + function setDatetime (pDatetime) { + try { + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> Entering function.') } - getNextFile(); + if (pDatetime === undefined) { + if (ERROR_LOG === true) { logger.write('[ERROR] setDatetime -> Received undefined datetime.') } + return + } - function getNextFile() { + cursorDate = pDatetime + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] setDatetime -> err = ' + err) } + } + } - try { + function reload (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] reload -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> Entering function."); } + getFiles(callBackFunction) - let targetDate = new Date(cursorDate); - targetDate.setUTCDate(targetDate.getUTCDate() + j); + collectGarbage(callBackFunction) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] reload -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + + function getFiles (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> Entering function.') } + + let i = 0 + let j = 0 + + let dateString + + getNextFile() + + function getNextFile () { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> Entering function.') } + + let targetDate = new Date(cursorDate) + targetDate.setUTCDate(targetDate.getUTCDate() + j) /* Small algorith to allow load first the current date, then alternate between the most forwad and the most backwards ones. */ - if (j === 0) { j++; } - else { - if (j < 0) { - j = -j; - j++; - } - else { - j = -j; - } - } - - let compareTargetDate = new Date(targetDate.toDateString()); - - if (beginDateRange !== undefined) { - - let compareBeginDate = new Date(beginDateRange.toDateString()); - - if (compareTargetDate.valueOf() < compareBeginDate.valueOf()) { - - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> compareTargetDate < compareBeginDate -> Not loading the file for this date."); } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> compareTargetDate < compareBeginDate -> compareTargetDate = " + compareTargetDate); } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> compareTargetDate < compareBeginDate -> compareBeginDate = " + compareBeginDate); } - - controlLoop(); - return; - } - } - - if (endDateRange !== undefined) { - - let compareEndDate = new Date(endDateRange.toDateString()); - - if (compareTargetDate.valueOf() > compareEndDate.valueOf()) { - - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> compareTargetDate > compareEndDate -> Not loading the file for this date."); } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> compareTargetDate > compareEndDate -> compareTargetDate = " + compareTargetDate); } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> getNextFile -> compareTargetDate > compareEndDate -> compareEndDate = " + compareEndDate); } - - controlLoop(); - return; - } - } - - dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2); - - let currentDay = Math.trunc((new Date()).valueOf() / (24 * 60 * 60 * 1000)); - let targetDay = Math.trunc(targetDate.valueOf() / (24 * 60 * 60 * 1000)); - - if (targetDay > currentDay) { - - controlLoop(); - - } else { - - if (thisObject.files.get(dateString) === undefined) { // We dont reload files we already have. - - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, targetDate, undefined, undefined, onFileReceived); - - } else { - - controlLoop(); - } - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFiles -> getNextFile -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + if (j === 0) { j++ } else { + if (j < 0) { + j = -j + j++ + } else { + j = -j } + } - function onFileReceived(err, file) { + let compareTargetDate = new Date(targetDate.toDateString()) - try { + if (beginDateRange !== undefined) { + let compareBeginDate = new Date(beginDateRange.toDateString()) - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> onFileReceived -> Entering function."); } + if (compareTargetDate.valueOf() < compareBeginDate.valueOf()) { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> compareTargetDate < compareBeginDate -> Not loading the file for this date.') } + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> compareTargetDate < compareBeginDate -> compareTargetDate = ' + compareTargetDate) } + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> compareTargetDate < compareBeginDate -> compareBeginDate = ' + compareBeginDate) } - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> onFileReceived -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> onFileReceived -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> onFileReceived -> err.message = " + err.message); } - - if (err.message === "File does not exist.") { - - controlLoop(); - return; - - } else { - - callBackFunction(err); - return; - } - - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> onFileReceived -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - thisObject.files.set(dateString, file); - - controlLoop(); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFiles -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + controlLoop() + return } + } - function controlLoop() { + if (endDateRange !== undefined) { + let compareEndDate = new Date(endDateRange.toDateString()) - try { + if (compareTargetDate.valueOf() > compareEndDate.valueOf()) { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> compareTargetDate > compareEndDate -> Not loading the file for this date.') } + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> compareTargetDate > compareEndDate -> compareTargetDate = ' + compareTargetDate) } + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> getNextFile -> compareTargetDate > compareEndDate -> compareEndDate = ' + compareEndDate) } - if (INFO_LOG === true) { logger.write("[INFO] getFiles -> controlLoop -> Entering function."); } - - if (callBackFunction !== undefined) { - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - } - - i++; - - if (i < minCursorSize) { - - getNextFile(); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFiles -> controlLoop -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + controlLoop() + return } + } + dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2) + + let currentDay = Math.trunc((new Date()).valueOf() / (24 * 60 * 60 * 1000)) + let targetDay = Math.trunc(targetDate.valueOf() / (24 * 60 * 60 * 1000)) + + if (targetDay > currentDay) { + controlLoop() + } else { + if (thisObject.files.get(dateString) === undefined) { + // We dont reload files we already have. + + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, targetDate, undefined, undefined, onFileReceived) + } else { + controlLoop() + } + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] getFiles -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] getFiles -> getNextFile -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } - } - - function collectGarbage(callBackFunction) { + } + function onFileReceived (err, file) { try { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> onFileReceived -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] collectGarbage -> Entering function."); } - - date = removeTime(cursorDate); - - let minDate = date.valueOf() - maxCursorSize * ONE_DAY_IN_MILISECONDS / 2; - let maxDate = date.valueOf() + maxCursorSize * ONE_DAY_IN_MILISECONDS / 2; - - for (let key of thisObject.files.keys()) { - - let keyDate = new Date(key); - - if (keyDate.valueOf() < minDate || keyDate.valueOf() > maxDate) { - - thisObject.files.delete(key); - - } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> onFileReceived -> Received OK Response.') } + break } + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> onFileReceived -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> onFileReceived -> err.message = ' + err.message) } + + if (err.message === 'File does not exist.') { + controlLoop() + return + } else { + callBackFunction(err) + return + } + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> onFileReceived -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + thisObject.files.set(dateString, file) + + controlLoop() } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] collectGarbage -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] getFiles -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + function controlLoop () { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFiles -> controlLoop -> Entering function.') } + + if (callBackFunction !== undefined) { + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + } + + i++ + + if (i < minCursorSize) { + getNextFile() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getFiles -> controlLoop -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getFiles -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function getExpectedFiles() { + function collectGarbage (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] collectGarbage -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getExpectedFiles -> Entering function."); } + date = removeTime(cursorDate) - return minCursorSize; + let minDate = date.valueOf() - maxCursorSize * ONE_DAY_IN_MILISECONDS / 2 + let maxDate = date.valueOf() + maxCursorSize * ONE_DAY_IN_MILISECONDS / 2 + for (let key of thisObject.files.keys()) { + let keyDate = new Date(key) + + if (keyDate.valueOf() < minDate || keyDate.valueOf() > maxDate) { + thisObject.files.delete(key) + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] collectGarbage -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } -} \ No newline at end of file + function getExpectedFiles () { + if (INFO_LOG === true) { logger.write('[INFO] getExpectedFiles -> Entering function.') } + + return minCursorSize + } +} diff --git a/Files/FileSequence.js b/Files/FileSequence.js index 5028143d4..55fca7746 100644 --- a/Files/FileSequence.js +++ b/Files/FileSequence.js @@ -1,219 +1,192 @@ - -function newFileSequence() { +  +function newFileSequence () { + const MODULE_NAME = 'File Sequence' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "File Sequence"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { + eventHandler: undefined, + getFile: getFile, + getExpectedFiles: getExpectedFiles, + getFilesLoaded: getFilesLoaded, + initialize: initialize, + finalize: finalize + } - let thisObject = { - eventHandler: undefined, - getFile: getFile, - getExpectedFiles: getExpectedFiles, - getFilesLoaded: getFilesLoaded, - initialize: initialize, - finalize: finalize + let filesLoaded = 0 + let fileCloud + let files = new Map() + let maxSequence = -1 // This is replaced by the content of the sequence file, which contains an index that starts on zero. In the case that the sequence file is not found the default value is -1 so when you add 1 it gives you the amount of files in the sequence, zero. + let market + let devTeam + let bot + let thisSet + let product + + thisObject.eventHandler = newEventHandler() + + let intervalHandle + + return thisObject + + function finalize () { + try { + if (INFO_LOG === true) { logger.write('[INFO] finalize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] finalize -> devTeam = ' + devTeam.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] finalize -> bot = ' + bot.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] finalize -> thisSet = ' + thisSet.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] finalize -> intervalHandle = ' + intervalHandle) } + + clearInterval(intervalHandle) + + filesLoaded = undefined + fileCloud = undefined + files = undefined + maxSequence = undefined + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] finalize -> err = ' + err) } } + } - let filesLoaded = 0; - let fileCloud; - let files = new Map; - let maxSequence = -1; // This is replaced by the content of the sequence file, which contains an index that starts on zero. In the case that the sequence file is not found the default value is -1 so when you add 1 it gives you the amount of files in the sequence, zero. - let market; - let devTeam; - let bot; - let thisSet; - let product; + function initialize (pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - thisObject.eventHandler = newEventHandler(); + exchange = ecosystem.getExchange(pProduct, pExchange) - let intervalHandle; + if (exchange === undefined) { + throw 'Exchange not supoorted by this pProduct of the ecosystem! - pDevTeam.codeName = ' + pDevTeam.codeName + ', pBot.codeName = ' + pBot.codeName + ', pProduct.codeName = ' + pProduct.codeName + ', pExchange = ' + pExchange + } - return thisObject; + intervalHandle = setInterval(updateFiles, _1_MINUTE_IN_MILISECONDS) - function finalize() { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> intervalHandle = ' + intervalHandle) } - try { + market = pMarket + devTeam = pDevTeam + bot = pBot + thisSet = pSet + product = pProduct - if (INFO_LOG === true) { logger.write("[INFO] finalize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] finalize -> devTeam = " + devTeam.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] finalize -> bot = " + bot.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] finalize -> thisSet = " + thisSet.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] finalize -> intervalHandle = " + intervalHandle); } - - clearInterval(intervalHandle); - - filesLoaded = undefined; - fileCloud = undefined; - files = undefined; - maxSequence = undefined; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] finalize -> err = " + err); } - } - } - - function initialize(pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - exchange = ecosystem.getExchange(pProduct, pExchange); - - if (exchange === undefined) { - - throw "Exchange not supoorted by this pProduct of the ecosystem! - pDevTeam.codeName = " + pDevTeam.codeName + ", pBot.codeName = " + pBot.codeName + ", pProduct.codeName = " + pProduct.codeName + ", pExchange = " + pExchange; - - } - - intervalHandle = setInterval(updateFiles, _1_MINUTE_IN_MILISECONDS); - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> intervalHandle = " + intervalHandle); } - - market = pMarket; - devTeam = pDevTeam; - bot = pBot; - thisSet = pSet; - product = pProduct; - - fileCloud = newFileCloud(); - fileCloud.initialize(bot); + fileCloud = newFileCloud() + fileCloud.initialize(bot) /* First we will get the sequence max number */ - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, "Sequence", undefined, onSequenceFileReceived); + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, 'Sequence', undefined, onSequenceFileReceived) - function onSequenceFileReceived(err, file) { + function onSequenceFileReceived (err, file) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> key = ' + devTeam.codeName + '-' + bot.codeName + '-' + product.codeName) } - try { + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> Received OK Response.') } + break + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> key = " + devTeam.codeName + "-" + bot.codeName + "-" + product.codeName); } + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + case GLOBAL.CUSTOM_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> Received CUSTOM OK Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> err.message = ' + err.message) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> Received OK Response."); } - break; - } + callBackFunction(err) + return + } - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> err.message = ' + err.message) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } + callBackFunction(err, thisObject) + return + } - case GLOBAL.CUSTOM_OK_RESPONSE.result: { + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> Received CUSTOM OK Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> err.message = " + err.message); } + maxSequence = Number(file) - callBackFunction(err); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> err.message = " + err.message); } - - callBackFunction(err, thisObject); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - maxSequence = Number(file); - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> maxSequence = " + maxSequence); } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> maxSequence = ' + maxSequence) } /* Now we will get the sequence of files */ - for (let i = 0; i <= maxSequence; i++) { + for (let i = 0; i <= maxSequence; i++) { + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, i, undefined, onFileReceived) - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, i, undefined, onFileReceived); + function onFileReceived (err, file) { + try { + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { - function onFileReceived(err, file) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received OK Response.') } + break + } - try { + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received OK Response."); } - break; - } + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> err.message = ' + err.message) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } + callBackFunction(err) + return + } - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + default: { - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - files.set(i, file); - - filesLoaded++; - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE, thisObject); // Note that the callback is called for every file loaded. - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onSequenceFileReceived -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onSequenceFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSequenceFileReceived -> onFileReceived -> Received Unexpected Response.') } + callBackFunction(err) + return + } } + + files.set(i, file) + + filesLoaded++ + + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE, thisObject) // Note that the callback is called for every file loaded. + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onSequenceFileReceived -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } } - + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onSequenceFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function updateFiles() { + function updateFiles () { + try { + let updateFiles = 0 - try { - - let updateFiles = 0; - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> Entering function."); } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> Entering function.') } /* @@ -225,161 +198,137 @@ function newFileSequence() { */ - let currentMaxSequence = maxSequence; + let currentMaxSequence = maxSequence - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> currentMaxSequence = " + currentMaxSequence); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> intervalHandle = " + intervalHandle); } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> currentMaxSequence = ' + currentMaxSequence) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> intervalHandle = ' + intervalHandle) } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> devTeam = " + devTeam.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> bot = " + bot.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> thisSet = " + thisSet.codeName); } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> devTeam = ' + devTeam.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> bot = ' + bot.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> thisSet = ' + thisSet.codeName) } - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, "Sequence", undefined, onSequenceFileReceived); + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, 'Sequence', undefined, onSequenceFileReceived) - function onSequenceFileReceived(err, file) { + function onSequenceFileReceived (err, file) { + try { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> key = ' + devTeam.codeName + '-' + bot.codeName + '-' + product.codeName) } - try { + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> Received OK Response.') } + break + } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> key = " + devTeam.codeName + "-" + bot.codeName + "-" + product.codeName); } + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> Received FAIL Response.') } + return + } - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + case GLOBAL.CUSTOM_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> Received CUSTOM OK Response.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> err.message = ' + err.message) } + return + } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> Received OK Response."); } - break; - } + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> err.message = ' + err.message) } + return + } - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + default: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> Received Unexpected Response.') } + return + } + } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> Received FAIL Response."); } - return; - } + maxSequence = Number(file) - case GLOBAL.CUSTOM_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> Received CUSTOM OK Response."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> err.message = " + err.message); } - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> err.message = " + err.message); } - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> Received Unexpected Response."); } - return; - } - } - - maxSequence = Number(file); - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> maxSequence = " + maxSequence); } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> maxSequence = ' + maxSequence) } /* Now we will get the sequence of files, but in this case only from the currentMaxSequence and above. */ - for (let i = currentMaxSequence; i <= maxSequence; i++) { + for (let i = currentMaxSequence; i <= maxSequence; i++) { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> i = ' + i) } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> i = " + i); } + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, i, undefined, onFileReceived) - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, undefined, undefined, i, undefined, onFileReceived); + function onFileReceived (err, file) { + try { + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { - function onFileReceived(err, file) { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received OK Response.') } + break + } - try { + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received FAIL Response.') } + return + } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received OK Response."); } - break; - } + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> err.message = ' + err.message) } + return + } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received FAIL Response."); } - return; - } + default: { - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> err.message = " + err.message); } - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received Unexpected Response."); } - return; - } - } - - files.set(i, file); - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> File Updated."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> i = " + i); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> file.length = " + file.length); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> filesLoaded = " + filesLoaded); } - - if (i !== currentMaxSequence) { - - filesLoaded++; - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> filesLoaded = " + filesLoaded); } - - } - - if (filesLoaded === maxSequence + 1) { - - thisObject.eventHandler.raiseEvent("Files Updated", undefined); - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Files Updated event Raised."); } - - } - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> onSequenceFileReceived -> onFileReceived -> err = " + err); } - } - } - } - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> onSequenceFileReceived -> err = " + err); } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Received Unexpected Response.') } + return + } } + + files.set(i, file) + + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> File Updated.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> i = ' + i) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> file.length = ' + file.length) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> filesLoaded = ' + filesLoaded) } + + if (i !== currentMaxSequence) { + filesLoaded++ + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> filesLoaded = ' + filesLoaded) } + } + + if (filesLoaded === maxSequence + 1) { + thisObject.eventHandler.raiseEvent('Files Updated', undefined) + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onSequenceFileReceived -> onFileReceived -> Files Updated event Raised.') } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> onSequenceFileReceived -> onFileReceived -> err = ' + err) } + } } - + } } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> err = " + err); } + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> onSequenceFileReceived -> err = ' + err) } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> err = ' + err) } } + } - function getFile(pSequence) { + function getFile (pSequence) { + if (INFO_LOG === true) { logger.write('[INFO] getFile -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] getFile -> pSequence = ' + pSequence) } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> pSequence = " + pSequence); } + return files.get(pSequence) + } - return files.get(pSequence); + function getExpectedFiles () { + if (INFO_LOG === true) { logger.write('[INFO] getExpectedFiles -> Entering function.') } - } + return maxSequence + 1 + } - function getExpectedFiles() { + function getFilesLoaded () { + if (INFO_LOG === true) { logger.write('[INFO] getFilesLoaded -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getExpectedFiles -> Entering function."); } - - return maxSequence + 1; - - } - - function getFilesLoaded() { - - if (INFO_LOG === true) { logger.write("[INFO] getFilesLoaded -> Entering function."); } - - return filesLoaded; - - } - -} \ No newline at end of file + return filesLoaded + } +} diff --git a/Files/MarketFiles.js b/Files/MarketFiles.js index 0bbf6d116..324a2c1f7 100644 --- a/Files/MarketFiles.js +++ b/Files/MarketFiles.js @@ -1,253 +1,210 @@ - -function newMarketFiles() { +  +function newMarketFiles () { + const MODULE_NAME = 'Market Files' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Market Files"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { + eventHandler: undefined, + getFile: getFile, + getExpectedFiles: getExpectedFiles, + getFilesLoaded: getFilesLoaded, + initialize: initialize, + finalize: finalize + } - let thisObject = { - eventHandler: undefined, - getFile: getFile, - getExpectedFiles: getExpectedFiles, - getFilesLoaded: getFilesLoaded, - initialize: initialize, - finalize: finalize + let filesLoaded = 0 + + let fileCloud + + let files = new Map() + + let market + let exchange + let devTeam + let bot + let thisSet + let periodName + + thisObject.eventHandler = newEventHandler() + + let intervalHandle + + return thisObject + + function finalize () { + try { + if (INFO_LOG === true) { logger.write('[INFO] finalize -> Entering function.') } + + clearInterval(intervalHandle) + + filesLoaded = undefined + files = undefined + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] finalize -> err = ' + err) } } + } - let filesLoaded = 0; + function initialize (pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - let fileCloud; + exchange = ecosystem.getExchange(pProduct, pExchange) - let files = new Map; + if (exchange === undefined) { + throw 'Exchange not supoorted by this pProduct of the ecosystem! - pDevTeam.codeName = ' + pDevTeam.codeName + ', pBot.codeName = ' + pBot.codeName + ', pProduct.codeName = ' + pProduct.codeName + ', pExchange = ' + pExchange + } - let market; - let exchange; - let devTeam; - let bot; - let thisSet; - let periodName; + intervalHandle = setInterval(updateFiles, _10_MINUTES_IN_MILISECONDS) - thisObject.eventHandler = newEventHandler(); + market = pMarket + devTeam = pDevTeam + bot = pBot + thisSet = pSet - let intervalHandle; - - return thisObject; - - function finalize() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] finalize -> Entering function."); } - - clearInterval(intervalHandle); - - filesLoaded = undefined; - files = undefined; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] finalize -> err = " + err); } - } - } - - function initialize(pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - exchange = ecosystem.getExchange(pProduct, pExchange); - - if (exchange === undefined) { - - throw "Exchange not supoorted by this pProduct of the ecosystem! - pDevTeam.codeName = " + pDevTeam.codeName + ", pBot.codeName = " + pBot.codeName + ", pProduct.codeName = " + pProduct.codeName + ", pExchange = " + pExchange; - - } - - intervalHandle = setInterval(updateFiles, _10_MINUTES_IN_MILISECONDS); - - market = pMarket; - devTeam = pDevTeam; - bot = pBot; - thisSet = pSet; - - fileCloud = newFileCloud(); - fileCloud.initialize(pBot); + fileCloud = newFileCloud() + fileCloud.initialize(pBot) /* Now we will get the market files */ - for (let i = 0; i < marketFilesPeriods.length; i++) { + for (let i = 0; i < marketFilesPeriods.length; i++) { + let periodTime = marketFilesPeriods[i][0] + let periodName = marketFilesPeriods[i][1] - let periodTime = marketFilesPeriods[i][0]; - let periodName = marketFilesPeriods[i][1]; + if (thisSet.validPeriods.includes(periodName) === true) { + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, undefined, undefined, undefined, onFileReceived) - if (thisSet.validPeriods.includes(periodName) === true) { + function onFileReceived (err, file) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Entering function.') } - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, undefined, undefined, undefined, onFileReceived); - - function onFileReceived(err, file) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - files.set(periodTime, file); - - filesLoaded++; - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE, thisObject); // Note that the callback is called for every file loaded. - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received OK Response.') } + break } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> err.message = ' + err.message) } + + callBackFunction(err) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + files.set(periodTime, file) + + filesLoaded++ + + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE, thisObject) // Note that the callback is called for every file loaded. + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } - - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function updateFiles() { + function updateFiles () { + try { + let updateFiles = 0 - try { - - let updateFiles = 0; - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> Entering function."); } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> Entering function.') } /* Now we will get the market files */ - for (let i = 0; i < marketFilesPeriods.length; i++) { + for (let i = 0; i < marketFilesPeriods.length; i++) { + let periodTime = marketFilesPeriods[i][0] + let periodName = marketFilesPeriods[i][1] - let periodTime = marketFilesPeriods[i][0]; - let periodName = marketFilesPeriods[i][1]; + if (thisSet.validPeriods.includes(periodName) === true) { + fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, undefined, undefined, undefined, onFileReceived) - if (thisSet.validPeriods.includes(periodName) === true) { + function onFileReceived (err, file) { + try { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Entering function.') } - fileCloud.getFile(devTeam, bot, thisSet, exchange, market, periodName, undefined, undefined, undefined, onFileReceived); - - function onFileReceived(err, file) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received FAIL Response."); } - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> err.message = " + err.message); } - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> Received Unexpected Response."); } - return; - } - } - - files.set(periodTime, file); - updateFiles++; - - if (updateFiles === marketFilesPeriods.length) { - - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> All files received. "); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> devTeam = " + devTeam.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> bot = " + bot.codeName); } - if (INFO_LOG === true) { logger.write("[INFO] updateFiles -> onFileReceived -> thisSet = " + thisSet.codeName); } - - thisObject.eventHandler.raiseEvent("Files Updated", undefined); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> onFileReceived -> err = " + err); } - } - } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received OK Response.') } + break } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received FAIL Response.') } + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> err.message = ' + err.message) } + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> Received Unexpected Response.') } + return + } + } + + files.set(periodTime, file) + updateFiles++ + + if (updateFiles === marketFilesPeriods.length) { + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> All files received. ') } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> devTeam = ' + devTeam.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> bot = ' + bot.codeName) } + if (INFO_LOG === true) { logger.write('[INFO] updateFiles -> onFileReceived -> thisSet = ' + thisSet.codeName) } + + thisObject.eventHandler.raiseEvent('Files Updated', undefined) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> onFileReceived -> err = ' + err) } } - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] updateFiles -> err = " + err); } + } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] updateFiles -> err = ' + err) } } + } - function getFile(pPeriod) { + function getFile (pPeriod) { + if (INFO_LOG === true) { logger.write('[INFO] getFile -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> Entering function."); } + return files.get(pPeriod) + } - return files.get(pPeriod); + function getExpectedFiles () { + if (INFO_LOG === true) { logger.write('[INFO] getExpectedFiles -> Entering function.') } - } + return marketFilesPeriods.length + } - function getExpectedFiles() { + function getFilesLoaded () { + if (INFO_LOG === true) { logger.write('[INFO] getFilesLoaded -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getExpectedFiles -> Entering function."); } - - return marketFilesPeriods.length; - - } - - function getFilesLoaded() { - - if (INFO_LOG === true) { logger.write("[INFO] getFilesLoaded -> Entering function."); } - - return filesLoaded; - - } - -} \ No newline at end of file + return filesLoaded + } +} diff --git a/Files/SingleFile.js b/Files/SingleFile.js index 65c8d8472..fe4c22914 100644 --- a/Files/SingleFile.js +++ b/Files/SingleFile.js @@ -1,105 +1,89 @@ - -function newSingleFile() { +  +function newSingleFile () { + const MODULE_NAME = 'Single File' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Single File"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { + getFile: getFile, + initialize: initialize + } - let thisObject = { - getFile: getFile, - initialize: initialize - } + let fileCloud + let file - let fileCloud; - let file; + return thisObject - return thisObject; + function initialize (pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - function initialize(pDevTeam, pBot, pProduct, pSet, pExchange, pMarket, callBackFunction) { + let exchange = ecosystem.getExchange(pProduct, pExchange) - try { + if (pExchange !== undefined && exchange === undefined) { + // We support no exchange as a parameter, but if provided, then it must be at the list of exchanges of that product. - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } + throw 'Exchange not supoorted by this pProduct of the ecosystem! - pDevTeam.codeName = ' + pDevTeam.codeName + ', pBot.codeName = ' + pBot.codeName + ', pProduct.codeName = ' + pProduct.codeName + ', pExchange = ' + pExchange + } - let exchange = ecosystem.getExchange(pProduct, pExchange); - - if (pExchange !== undefined && exchange === undefined) { // We support no exchange as a parameter, but if provided, then it must be at the list of exchanges of that product. - - throw "Exchange not supoorted by this pProduct of the ecosystem! - pDevTeam.codeName = " + pDevTeam.codeName + ", pBot.codeName = " + pBot.codeName + ", pProduct.codeName = " + pProduct.codeName + ", pExchange = " + pExchange; - - } - - fileCloud = newFileCloud(); - fileCloud.initialize(pBot); + fileCloud = newFileCloud() + fileCloud.initialize(pBot) /* Now we will get the file */ - fileCloud.getFile(pDevTeam, pBot, pSet, exchange, pMarket, undefined, undefined, undefined, undefined, onFileReceived); + fileCloud.getFile(pDevTeam, pBot, pSet, exchange, pMarket, undefined, undefined, undefined, undefined, onFileReceived) - function onFileReceived(err, pFile) { + function onFileReceived (err, pFile) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Entering function.') } - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileReceived -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - file = pFile; - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileReceived -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received OK Response.') } + break } + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> err.message = ' + err.message) } + + callBackFunction(err) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileReceived -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + file = pFile + + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileReceived -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function getFile() { + function getFile () { + if (INFO_LOG === true) { logger.write('[INFO] getFile -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getFile -> Entering function."); } - - return file; - - } - -} \ No newline at end of file + return file + } +} diff --git a/FloatingSpace/FloatingLayer.js b/FloatingSpace/FloatingLayer.js index 0159118cd..d7f33cf61 100644 --- a/FloatingSpace/FloatingLayer.js +++ b/FloatingSpace/FloatingLayer.js @@ -1,6 +1,5 @@ - -function newFloatingLayer() { - +  +function newFloatingLayer () { /* This module represent one layer of many possible layers that could be at the Floating Space. Objects in the same layer are subject to the same physics, and by being at the same level, they interact with each other. For example, they can bounce when one hit the other. @@ -14,23 +13,23 @@ function newFloatingLayer() { 2. Notes: Notes are a rectangular area where some text is posted. It has a subject and a body. */ - const MODULE_NAME = "Floating Layer"; - const INFO_LOG = false; - let INTENSIVE_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + const MODULE_NAME = 'Floating Layer' + const INFO_LOG = false + let INTENSIVE_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - let thisObject = { - addFloatingObject: addFloatingObject, - killFloatingObject: killFloatingObject, - getFloatingObject: getFloatingObject, - physicsLoop: physicsLoop, - isInside: isInside, - isInsideFloatingObject: isInsideFloatingObject, - changeTargetRepulsion: changeTargetRepulsion, - initialize: initialize - }; + let thisObject = { + addFloatingObject: addFloatingObject, + killFloatingObject: killFloatingObject, + getFloatingObject: getFloatingObject, + physicsLoop: physicsLoop, + isInside: isInside, + isInsideFloatingObject: isInsideFloatingObject, + changeTargetRepulsion: changeTargetRepulsion, + initialize: initialize + } /* When objects are added to this layer they are added to the invisibleFloatingObjects array and they stay there because they are invisible. @@ -40,7 +39,7 @@ function newFloatingLayer() { To save resources, the physics engine only apply its calculations to visible floating objects. */ - let invisibleFloatingObjects = []; + let invisibleFloatingObjects = [] /* Floating objects are accesible to plotters because they carry a "payload" object that was creted by them. This object includes the position @@ -50,258 +49,225 @@ function newFloatingLayer() { array. */ - let visibleFloatingObjects = []; + let visibleFloatingObjects = [] /* The creator of the floatingObject at any time can decide to get rid of it and kill it. But we dont want the object just to dissapear because that doesnt look good. What this module does is to remove it from the visible or invisible layer where they are and move them to the dyingFloatingObjects array. Object in this array have a short animation until they finally graphically dissapear and at thay point they are also - removed from the dying array for good. + removed from the dying array for good. */ - let dyingFloatingObjects = []; + let dyingFloatingObjects = [] - let maxTargetRepulsionForce = 0.003; - let currentHandle = 0; + let maxTargetRepulsionForce = 0.003 + let currentHandle = 0 - return thisObject; + return thisObject - function initialize(callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function initialize (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } /* We dont need to initialize anything right now. */ - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } - } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } } + } - function addFloatingObject(pFloatingObject, callBackFunction) { - + function addFloatingObject (pFloatingObject, callBackFunction) { /* As you can see here, even though the floating objects are created outside this layer, its creator it is not supossed to keep the reference to the object, so that the managment of the objects references can live entirely inside this module. What the creator keeps, is a handle to the object which it can use to retrieve the floating object when needed. */ - try { + try { + if (INFO_LOG === true) { logger.write('[INFO] addFloatingObject -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] addFloatingObject -> Entering function."); } + invisibleFloatingObjects.push(pFloatingObject) - invisibleFloatingObjects.push(pFloatingObject); + if (INFO_LOG === true) { logger.write('[INFO] addFloatingObject -> invisibleFloatingObjects.length = ' + invisibleFloatingObjects.length) } - if (INFO_LOG === true) { logger.write("[INFO] addFloatingObject -> invisibleFloatingObjects.length = " + invisibleFloatingObjects.length); } + currentHandle++ - currentHandle++; + pFloatingObject.handle = currentHandle // Math.floor((Math.random() * 10000000) + 1); - pFloatingObject.handle = currentHandle; //Math.floor((Math.random() * 10000000) + 1); + if (INFO_LOG === true) { logger.write('[INFO] addFloatingObject -> pFloatingObject.handle = ' + pFloatingObject.handle) } + if (INFO_LOG === true) { logger.write('[INFO] addFloatingObject -> pFloatingObject.type = ' + pFloatingObject.type) } - if (INFO_LOG === true) { logger.write("[INFO] addFloatingObject -> pFloatingObject.handle = " + pFloatingObject.handle); } - if (INFO_LOG === true) { logger.write("[INFO] addFloatingObject -> pFloatingObject.type = " + pFloatingObject.type); } - - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] addFloatingObject -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } - } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] addFloatingObject -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } } + } - function killFloatingObject(pFloatingObjectHandle, callBackFunction) { - - try { - + function killFloatingObject (pFloatingObjectHandle, callBackFunction) { + try { /* The floting object to be killed can be either at the visible or the invisible array. What we do here is look for it at each of the arrays until we find it. Once found, we remove it and is sent to the dying floating objects array. */ - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> Entering function."); } + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> Entering function.') } - for (let i = 0; i < invisibleFloatingObjects.length; i++) { + for (let i = 0; i < invisibleFloatingObjects.length; i++) { + let floatingObject = invisibleFloatingObjects[i] - let floatingObject = invisibleFloatingObjects[i]; + if (floatingObject.handle === pFloatingObjectHandle) { + invisibleFloatingObjects.splice(i, 1) // Delete item from array. - if (floatingObject.handle === pFloatingObjectHandle) { - invisibleFloatingObjects.splice(i, 1); // Delete item from array. + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> floatingObject.handle = ' + floatingObject.handle) } + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> Removing floatingObject from invisibleFloatingObjects.') } + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> invisibleFloatingObjects.length = ' + invisibleFloatingObjects.length) } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> floatingObject.handle = " + floatingObject.handle); } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> Removing floatingObject from invisibleFloatingObjects."); } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> invisibleFloatingObjects.length = " + invisibleFloatingObjects.length); } + sendToDie(floatingObject) + return + } + } - sendToDie(floatingObject); - return; - } - } + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[i] - for (let i = 0; i < visibleFloatingObjects.length; i++) { + if (floatingObject.handle === pFloatingObjectHandle) { + visibleFloatingObjects.splice(i, 1) // Delete item from array. - let floatingObject = visibleFloatingObjects[i]; + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> floatingObject.handle = ' + floatingObject.handle) } + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> Removing floatingObject from visibleFloatingObjects.') } + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> visibleFloatingObjects.length = ' + visibleFloatingObjects.length) } - if (floatingObject.handle === pFloatingObjectHandle) { - visibleFloatingObjects.splice(i, 1); // Delete item from array. + sendToDie(floatingObject) + return + } + } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> floatingObject.handle = " + floatingObject.handle); } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> Removing floatingObject from visibleFloatingObjects."); } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> visibleFloatingObjects.length = " + visibleFloatingObjects.length); } + if (ERROR_LOG === true) { logger.write('[ERROR] killFloatingObject -> Floating Object Not Found.') } + if (ERROR_LOG === true) { logger.write('[ERROR] killFloatingObject -> Floating Object cannot be killed.') } + if (ERROR_LOG === true) { logger.write('[ERROR] killFloatingObject -> pFloatingObjectHandle = ' + pFloatingObjectHandle) } - sendToDie(floatingObject); - return; - } - } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } - if (ERROR_LOG === true) { logger.write("[ERROR] killFloatingObject -> Floating Object Not Found."); } - if (ERROR_LOG === true) { logger.write("[ERROR] killFloatingObject -> Floating Object cannot be killed."); } - if (ERROR_LOG === true) { logger.write("[ERROR] killFloatingObject -> pFloatingObjectHandle = " + pFloatingObjectHandle); } - - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } - - function sendToDie(pFloatingObject) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> sendToDie -> Entering function."); } + function sendToDie (pFloatingObject) { + try { + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> sendToDie -> Entering function.') } /* Lets mofigy the targerRadius */ - pFloatingObject.targetRadius = 0; + pFloatingObject.targetRadius = 0 /* Lets transfer the payload to a new payload structure. */ - let payload = {}; + let payload = {} - switch (pFloatingObject.type) { + switch (pFloatingObject.type) { - case "Profile Ball": { + case 'Profile Ball': { + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> sendToDie -> Profile Ball -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> sendToDie -> Profile Ball -> Entering function."); } + if (pFloatingObject.payload.profile.visible === false) { return } - if (pFloatingObject.payload.profile.visible === false) { return; } + payload.profile = { + position: { + x: pFloatingObject.payload.profile.position.x, + y: pFloatingObject.payload.profile.position.y + }, + visible: pFloatingObject.payload.profile.visible, + botAvatar: pFloatingObject.payload.profile.botAvatar + } - payload.profile = { - position: { - x: pFloatingObject.payload.profile.position.x, - y: pFloatingObject.payload.profile.position.y - }, - visible: pFloatingObject.payload.profile.visible, - botAvatar: pFloatingObject.payload.profile.botAvatar - } - - pFloatingObject.payload = payload; - break; - } - case "Note": { - - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> sendToDie -> Note -> Entering function."); } - - if (pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].visible === false) { return; } - - payload.notes = []; - let note = { - title: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].title, - body: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].body, - date: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].date, - rate: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].rate, - position: { - x: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.x, - y: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.y - }, - visible: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].visible - }; - payload.notes.push(note); - pFloatingObject.payloadNoteIndex = 0; - - pFloatingObject.payload = payload; - break; - } - default: { - - break; - } - } - - dyingFloatingObjects.push(pFloatingObject); - - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> sendToDie -> Adding floatingObject to dyingFloatingObjects."); } - if (INFO_LOG === true) { logger.write("[INFO] killFloatingObject -> sendToDie -> dyingFloatingObjects.length = " + dyingFloatingObjects.length); } - - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] killFloatingObject -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } - } + pFloatingObject.payload = payload + break } + case 'Note': { + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> sendToDie -> Note -> Entering function.') } + if (pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].visible === false) { return } + + payload.notes = [] + let note = { + title: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].title, + body: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].body, + date: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].date, + rate: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].rate, + position: { + x: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.x, + y: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.y + }, + visible: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].visible + } + payload.notes.push(note) + pFloatingObject.payloadNoteIndex = 0 + + pFloatingObject.payload = payload + break + } + default: { + break + } + } + + dyingFloatingObjects.push(pFloatingObject) + + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> sendToDie -> Adding floatingObject to dyingFloatingObjects.') } + if (INFO_LOG === true) { logger.write('[INFO] killFloatingObject -> sendToDie -> dyingFloatingObjects.length = ' + dyingFloatingObjects.length) } + + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] killFloatingObject -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } + if (ERROR_LOG === true) { logger.write('[ERROR] killFloatingObject -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] killFloatingObject -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } } + } - function getFloatingObject(pFloatingObjectHandle, pFloatingObjectIndex) { - + function getFloatingObject (pFloatingObjectHandle, pFloatingObjectIndex) { /* There are two ways to look for a floating object: by handle or by index. The search by handle is done on the visible and invisible array. The search by index is done only on the visible ones. The search by index is usually needed when mouse events occurs. In those cases only objects visible to the end usser matters. */ - try { + try { + if (INFO_LOG === true) { logger.write('[INFO] getFloatingObject -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getFloatingObject -> Entering function."); } + if (pFloatingObjectHandle !== undefined) { + for (let i = 0; i < invisibleFloatingObjects.length; i++) { + let floatingObject = invisibleFloatingObjects[i] - if (pFloatingObjectHandle !== undefined) { - - for (let i = 0; i < invisibleFloatingObjects.length; i++) { - - let floatingObject = invisibleFloatingObjects[i]; - - if (floatingObject.handle === pFloatingObjectHandle) { - - return floatingObject; - } - } - - for (let i = 0; i < visibleFloatingObjects.length; i++) { - - let floatingObject = visibleFloatingObjects[i]; - - if (floatingObject.handle === pFloatingObjectHandle) { - - return floatingObject; - } - } - } - - if (pFloatingObjectIndex !== undefined) { - - for (let i = 0; i < visibleFloatingObjects.length; i++) { - - let floatingObject = visibleFloatingObjects[i]; - - if (i === pFloatingObjectIndex) { - - return floatingObject; - } - } - } - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] getFloatingObject -> err.message = " + err.message); } + if (floatingObject.handle === pFloatingObjectHandle) { + return floatingObject + } } - } + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[i] + + if (floatingObject.handle === pFloatingObjectHandle) { + return floatingObject + } + } + } + + if (pFloatingObjectIndex !== undefined) { + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[i] + + if (i === pFloatingObjectIndex) { + return floatingObject + } + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] getFloatingObject -> err.message = ' + err.message) } + } + } /******************************************/ /* */ @@ -309,8 +275,7 @@ function newFloatingLayer() { /* */ /******************************************/ - function physicsLoop() { - + function physicsLoop () { /* The Physics engine is hooked at the animation loop, so it executes very very often. According to this Physics engine, each floating object has a position and a speed. In fact, each floating object has two positions at the same time: @@ -321,809 +286,704 @@ function newFloatingLayer() { The anchor position influences the current position, since the Physics engine will apply a gravity force to the ball's position in order to make it gravitate towards the anchor position. At the same time there will be a repulsion force that will prevent the ball reaching - the anchor position, so that the anchor point keeps visible to the user. + the anchor position, so that the anchor point keeps visible to the user. */ - try { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> Entering function.') } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> Entering function."); } - - applyPhysics(); - - function applyPhysics() { + applyPhysics() + function applyPhysics () { /* This function makes all the calculations to apply phisycs on all visible floatingObjects in this layer. */ - try { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> applyPhysics -> Entering function.') } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> applyPhysics -> Entering function."); } + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[i] - for (let i = 0; i < visibleFloatingObjects.length; i++) { - - let floatingObject = visibleFloatingObjects[i]; + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> Change position based on speed.') } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> Change position based on speed."); } + floatingObject.currentPosition.x = floatingObject.currentPosition.x + floatingObject.currentSpeed.x + floatingObject.currentPosition.y = floatingObject.currentPosition.y + floatingObject.currentSpeed.y - floatingObject.currentPosition.x = floatingObject.currentPosition.x + floatingObject.currentSpeed.x; - floatingObject.currentPosition.y = floatingObject.currentPosition.y + floatingObject.currentSpeed.y; + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> Apply some friction to desaccelerate.') } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> Apply some friction to desaccelerate."); } + floatingObject.currentSpeed.x = floatingObject.currentSpeed.x * floatingObject.friction // Desaceleration factor. + floatingObject.currentSpeed.y = floatingObject.currentSpeed.y * floatingObject.friction // Desaceleration factor. - floatingObject.currentSpeed.x = floatingObject.currentSpeed.x * floatingObject.friction; // Desaceleration factor. - floatingObject.currentSpeed.y = floatingObject.currentSpeed.y * floatingObject.friction; // Desaceleration factor. + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> Gives a minimun speed towards their taget.') } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> Gives a minimun speed towards their taget."); } + let payload = { + position: undefined, + visible: false + } - let payload = { - position: undefined, - visible: false - }; + switch (floatingObject.type) { - switch (floatingObject.type) { + case 'Profile Ball': { + payload.position = floatingObject.payload.profile.position + payload.visible = floatingObject.payload.profile.visible + break + } + case 'Note': { + payload.position = floatingObject.payload.notes[floatingObject.payloadNoteIndex].position + payload.visible = floatingObject.payload.notes[floatingObject.payloadNoteIndex].visible - case "Profile Ball": { + break + } + default: { + break + } + } - payload.position = floatingObject.payload.profile.position; - payload.visible = floatingObject.payload.profile.visible; - break; - } - case "Note": { + if (floatingObject.currentPosition.x < payload.position.x) { + floatingObject.currentSpeed.x = floatingObject.currentSpeed.x + 0.005 + } else { + floatingObject.currentSpeed.x = floatingObject.currentSpeed.x - 0.005 + } - payload.position = floatingObject.payload.notes[floatingObject.payloadNoteIndex].position; - payload.visible = floatingObject.payload.notes[floatingObject.payloadNoteIndex].visible; + if (floatingObject.currentPosition.y < payload.position.y) { + floatingObject.currentSpeed.y = floatingObject.currentSpeed.y + 0.005 + } else { + floatingObject.currentSpeed.y = floatingObject.currentSpeed.y - 0.005 + } - break; - } - default: { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> Set a maximun speed.') } - break; - } - } + const MAX_SPEED = 50 - if (floatingObject.currentPosition.x < payload.position.x) { - floatingObject.currentSpeed.x = floatingObject.currentSpeed.x + .005; - } else { - floatingObject.currentSpeed.x = floatingObject.currentSpeed.x - .005; - } + if (floatingObject.currentSpeed.x > MAX_SPEED) { + floatingObject.currentSpeed.x = MAX_SPEED + } - if (floatingObject.currentPosition.y < payload.position.y) { - floatingObject.currentSpeed.y = floatingObject.currentSpeed.y + .005; - } else { - floatingObject.currentSpeed.y = floatingObject.currentSpeed.y - .005; - } + if (floatingObject.currentSpeed.y > MAX_SPEED) { + floatingObject.currentSpeed.y = MAX_SPEED + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> Set a maximun speed."); } + if (floatingObject.currentSpeed.x < -MAX_SPEED) { + floatingObject.currentSpeed.x = -MAX_SPEED + } - const MAX_SPEED = 50; - - if (floatingObject.currentSpeed.x > MAX_SPEED) { - floatingObject.currentSpeed.x = MAX_SPEED; - } - - if (floatingObject.currentSpeed.y > MAX_SPEED) { - floatingObject.currentSpeed.y = MAX_SPEED; - } - - if (floatingObject.currentSpeed.x < -MAX_SPEED) { - floatingObject.currentSpeed.x = -MAX_SPEED; - } - - if (floatingObject.currentSpeed.y < -MAX_SPEED) { - floatingObject.currentSpeed.y = -MAX_SPEED; - } + if (floatingObject.currentSpeed.y < -MAX_SPEED) { + floatingObject.currentSpeed.y = -MAX_SPEED + } // The radius also have a target. - if (Math.abs(floatingObject.currentRadius - floatingObject.targetRadius) >= 1) { - - if (floatingObject.currentRadius < floatingObject.targetRadius) { - floatingObject.currentRadius = floatingObject.currentRadius + .5; - } else { - floatingObject.currentRadius = floatingObject.currentRadius - .5; - } - } + if (Math.abs(floatingObject.currentRadius - floatingObject.targetRadius) >= 1) { + if (floatingObject.currentRadius < floatingObject.targetRadius) { + floatingObject.currentRadius = floatingObject.currentRadius + 0.5 + } else { + floatingObject.currentRadius = floatingObject.currentRadius - 0.5 + } + } // The imageSize also have a target. - if (Math.abs(floatingObject.currentImageSize - floatingObject.targetImageSize) >= 1) { - - if (floatingObject.currentImageSize < floatingObject.targetImageSize) { - floatingObject.currentImageSize = floatingObject.currentImageSize + 1; - } else { - floatingObject.currentImageSize = floatingObject.currentImageSize - 1; - } - } + if (Math.abs(floatingObject.currentImageSize - floatingObject.targetImageSize) >= 1) { + if (floatingObject.currentImageSize < floatingObject.targetImageSize) { + floatingObject.currentImageSize = floatingObject.currentImageSize + 1 + } else { + floatingObject.currentImageSize = floatingObject.currentImageSize - 1 + } + } // The fontSize also have a target. - if (Math.abs(floatingObject.currentFontSize - floatingObject.targetFontSize) >= 0.2) { - - if (floatingObject.currentFontSize < floatingObject.targetFontSize) { - floatingObject.currentFontSize = floatingObject.currentFontSize + 0.2; - } else { - floatingObject.currentFontSize = floatingObject.currentFontSize - 0.2; - } - } + if (Math.abs(floatingObject.currentFontSize - floatingObject.targetFontSize) >= 0.2) { + if (floatingObject.currentFontSize < floatingObject.targetFontSize) { + floatingObject.currentFontSize = floatingObject.currentFontSize + 0.2 + } else { + floatingObject.currentFontSize = floatingObject.currentFontSize - 0.2 + } + } // We let the Floating Object animate the physics loops by itself. - floatingObject.physicsLoop(); - + floatingObject.physicsLoop() + /* Collision Control */ - for (let k = i + 1; k < visibleFloatingObjects.length; k++) { - - if (colliding(visibleFloatingObjects[i], visibleFloatingObjects[k])) { - - resolveCollision(visibleFloatingObjects[k], visibleFloatingObjects[i]); - - } - } + for (let k = i + 1; k < visibleFloatingObjects.length; k++) { + if (colliding(visibleFloatingObjects[i], visibleFloatingObjects[k])) { + resolveCollision(visibleFloatingObjects[k], visibleFloatingObjects[i]) + } + } /* Calculate repulsion force produced by all other floatingObjects */ - currentRepulsionForce(i); + currentRepulsionForce(i) - targetRepulsionForce(i); + targetRepulsionForce(i) - gravityForce(floatingObject, payload); + gravityForce(floatingObject, payload) + } - } + drawVisibleObjects() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> applyPhysics -> err.message = ' + err.message) } + } + } - drawVisibleObjects(); - } - - catch(err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> applyPhysics -> err.message = " + err.message); } - - } - } - - function drawVisibleObjects() { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> drawVisibleObjects -> Entering function."); } + function drawVisibleObjects () { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> drawVisibleObjects -> Entering function.') } /* We draw all the visibleFloatingObjects. */ - for (let i = 0; i < visibleFloatingObjects.length; i++) { - let floatingObject = visibleFloatingObjects[i]; - floatingObject.drawBackground(); - } + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[i] + floatingObject.drawBackground() + } - for (let i = 0; i < visibleFloatingObjects.length; i++) { - let floatingObject = visibleFloatingObjects[visibleFloatingObjects.length - i - 1]; - floatingObject.drawForeground(); - } + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[visibleFloatingObjects.length - i - 1] + floatingObject.drawForeground() + } - makeVisible(); - } + makeVisible() + } catch (err) { + if (ERROR_LOG === true && INTENSIVE_LOG === true) { logger.write('[ERROR] physicsLoop -> drawVisibleObjects -> err.message = ' + err.message) } + } + } - catch (err) { - - if (ERROR_LOG === true && INTENSIVE_LOG === true) { logger.write("[ERROR] physicsLoop -> drawVisibleObjects -> err.message = " + err.message); } - - } - } - - function makeVisible() { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> makeVisible -> Entering function."); } + function makeVisible () { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> makeVisible -> Entering function.') } /* Now we check if any of the created FloatingObjects where enabled to run under the Physics Engine. */ - for (let i = 0; i < invisibleFloatingObjects.length; i++) { + for (let i = 0; i < invisibleFloatingObjects.length; i++) { + let floatingObject = invisibleFloatingObjects[i] - let floatingObject = invisibleFloatingObjects[i]; + let payload = { + position: undefined, + visible: false + } - let payload = { - position: undefined, - visible: false - }; + switch (floatingObject.type) { - switch (floatingObject.type) { + case 'Profile Ball': { + payload.position = floatingObject.payload.profile.position + payload.visible = floatingObject.payload.profile.visible + break + } + case 'Note': { + if (floatingObject.payload.notes[floatingObject.payloadNoteIndex] !== undefined) { + payload.position = floatingObject.payload.notes[floatingObject.payloadNoteIndex].position + payload.visible = floatingObject.payload.notes[floatingObject.payloadNoteIndex].visible + } - case "Profile Ball": { + break + } + default: { + break + } + } - payload.position = floatingObject.payload.profile.position; - payload.visible = floatingObject.payload.profile.visible; - break; - } - case "Note": { - - if (floatingObject.payload.notes[floatingObject.payloadNoteIndex] !== undefined) { - - payload.position = floatingObject.payload.notes[floatingObject.payloadNoteIndex].position; - payload.visible = floatingObject.payload.notes[floatingObject.payloadNoteIndex].visible; - } - - break; - } - default: { - - break; - } - } - - if (payload.visible === true) { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> payload.visible = " + payload.visible); } + if (payload.visible === true) { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> payload.visible = ' + payload.visible) } /* The first time that the floatingObject becomes visible, we need to do this. */ - floatingObject.radomizeCurrentPosition(payload.position); - floatingObject.radomizeCurrentSpeed(); + floatingObject.radomizeCurrentPosition(payload.position) + floatingObject.radomizeCurrentSpeed() - visibleFloatingObjects.push(floatingObject); + visibleFloatingObjects.push(floatingObject) - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject.handle = " + floatingObject.handle); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject added to visibleFloatingObjects"); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> visibleFloatingObjects.length = " + visibleFloatingObjects.length); } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject.handle = ' + floatingObject.handle) } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject added to visibleFloatingObjects') } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> visibleFloatingObjects.length = ' + visibleFloatingObjects.length) } - invisibleFloatingObjects.splice(i, 1); // Delete item from array. + invisibleFloatingObjects.splice(i, 1) // Delete item from array. - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject.handle = " + floatingObject.handle); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject removed from invisibleFloatingObjects"); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> invisibleFloatingObjects.length = " + invisibleFloatingObjects.length); } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject.handle = ' + floatingObject.handle) } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject removed from invisibleFloatingObjects') } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> invisibleFloatingObjects.length = ' + invisibleFloatingObjects.length) } - return; // Only one at the time. - - } - } - - makeInvisible(); - } - - catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> makeVisible -> err.message = " + err.message); } - - } + return // Only one at the time. } + } - function makeInvisible() { + makeInvisible() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> makeVisible -> err.message = ' + err.message) } + } + } - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> makeInvisible -> Entering function."); } + function makeInvisible () { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> makeInvisible -> Entering function.') } /* Finally we check if any of the currently visible floatingObjects has become invisible and must be removed from the Physics Engine. */ - for (let i = 0; i < visibleFloatingObjects.length; i++) { + for (let i = 0; i < visibleFloatingObjects.length; i++) { + let floatingObject = visibleFloatingObjects[i] - let floatingObject = visibleFloatingObjects[i]; - - let payload = { - position: undefined, - visible: true - }; - - switch (floatingObject.type) { - - case "Profile Ball": { - - payload.visible = floatingObject.payload.profile.visible; - break; - } - case "Note": { - - payload.visible = floatingObject.payload.notes[floatingObject.payloadNoteIndex].visible; - break; - } - default: { - - break; - } - } - - if (payload.visible === false) { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> payload.visible = " + payload.visible); } - - invisibleFloatingObjects.push(floatingObject); - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject.handle = " + floatingObject.handle); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject added to invisibleFloatingObjects"); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> invisibleFloatingObjects.length = " + invisibleFloatingObjects.length); } - - visibleFloatingObjects.splice(i, 1); // Delete item from array. - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject.handle = " + floatingObject.handle); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> floatingObject removed from visibleFloatingObjects"); } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> visibleFloatingObjects.length = " + visibleFloatingObjects.length); } - - return; // Only one at the time. - - } - } - - animateDyingObjects(); - } - - catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> makeInvisible -> err.message = " + err.message); } - - } + let payload = { + position: undefined, + visible: true } - function animateDyingObjects() { + switch (floatingObject.type) { - try { + case 'Profile Ball': { + payload.visible = floatingObject.payload.profile.visible + break + } + case 'Note': { + payload.visible = floatingObject.payload.notes[floatingObject.payloadNoteIndex].visible + break + } + default: { + break + } + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> animateDyingObjects -> Entering function."); } + if (payload.visible === false) { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> payload.visible = ' + payload.visible) } + + invisibleFloatingObjects.push(floatingObject) + + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject.handle = ' + floatingObject.handle) } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject added to invisibleFloatingObjects') } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> invisibleFloatingObjects.length = ' + invisibleFloatingObjects.length) } + + visibleFloatingObjects.splice(i, 1) // Delete item from array. + + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject.handle = ' + floatingObject.handle) } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> floatingObject removed from visibleFloatingObjects') } + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> visibleFloatingObjects.length = ' + visibleFloatingObjects.length) } + + return // Only one at the time. + } + } + + animateDyingObjects() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> makeInvisible -> err.message = ' + err.message) } + } + } + + function animateDyingObjects () { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> animateDyingObjects -> Entering function.') } /* We animate some parts of the dying objects */ - for (let i = 0; i < dyingFloatingObjects.length; i++) { + for (let i = 0; i < dyingFloatingObjects.length; i++) { + let floatingObject = dyingFloatingObjects[i] - let floatingObject = dyingFloatingObjects[i]; - - if (Math.abs(floatingObject.currentRadius - floatingObject.targetRadius) >= 5) { - - let speed = Math.random(); - - floatingObject.currentRadius = floatingObject.currentRadius - speed * 3; - - } else { + if (Math.abs(floatingObject.currentRadius - floatingObject.targetRadius) >= 5) { + let speed = Math.random() + floatingObject.currentRadius = floatingObject.currentRadius - speed * 3 + } else { /* Here is when the floatingObjects are definetelly killed. */ - dyingFloatingObjects.splice(i, 1); // Delete item from array. - break; // only one at the time. - } - } - - drawDyingObjects(); - } - - catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> animateDyingObjects -> err.message = " + err.message); } - - } + dyingFloatingObjects.splice(i, 1) // Delete item from array. + break // only one at the time. } + } - function drawDyingObjects() { + drawDyingObjects() + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> animateDyingObjects -> err.message = ' + err.message) } + } + } - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] physicsLoop -> drawDyingObjects -> Entering function."); } + function drawDyingObjects () { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] physicsLoop -> drawDyingObjects -> Entering function.') } /* We also draw all the dyingFloatingObjects */ - for (let i = 0; i < dyingFloatingObjects.length; i++) { - let floatingObject = dyingFloatingObjects[i]; - floatingObject.drawBackground(); - } - - for (let i = 0; i < dyingFloatingObjects.length; i++) { - let floatingObject = dyingFloatingObjects[dyingFloatingObjects.length - i - 1]; - floatingObject.drawForeground(); - } - } - - catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> drawDyingObjects -> err.message = " + err.message); } - - } - } + for (let i = 0; i < dyingFloatingObjects.length; i++) { + let floatingObject = dyingFloatingObjects[i] + floatingObject.drawBackground() + } + for (let i = 0; i < dyingFloatingObjects.length; i++) { + let floatingObject = dyingFloatingObjects[dyingFloatingObjects.length - i - 1] + floatingObject.drawForeground() + } } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> err.message = " + err.message); } + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> drawDyingObjects -> err.message = ' + err.message) } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> err.message = ' + err.message) } } + } - function gravityForce(floatingObject, payload) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] gravityForce -> Entering function."); } + function gravityForce (floatingObject, payload) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] gravityForce -> Entering function.') } /* We simulate a kind of gravity towards the target point of each floatingObject. This force will make the floatingObject to keep pushing to reach that point. */ - const coulomb = .00001; - const minForce = 0.01; + const coulomb = 0.00001 + const minForce = 0.01 - var d = Math.sqrt(Math.pow(payload.position.x - floatingObject.currentPosition.x, 2) + Math.pow(payload.position.y - floatingObject.currentPosition.y, 2)); // ... we calculate the distance ... + var d = Math.sqrt(Math.pow(payload.position.x - floatingObject.currentPosition.x, 2) + Math.pow(payload.position.y - floatingObject.currentPosition.y, 2)) // ... we calculate the distance ... - var force = coulomb * d * d / floatingObject.currentMass; // In this case the mass of the floatingObject affects the gravity force that it receives, that gives priority to target position to bigger floatingObjects. + var force = coulomb * d * d / floatingObject.currentMass // In this case the mass of the floatingObject affects the gravity force that it receives, that gives priority to target position to bigger floatingObjects. - if (force < minForce) { // We need this attraction force to overcome the friction we imposed to the system. - force = minForce; - } + if (force < minForce) { // We need this attraction force to overcome the friction we imposed to the system. + force = minForce + } - var pos1 = { - x: floatingObject.currentPosition.x, - y: floatingObject.currentPosition.y - }; + var pos1 = { + x: floatingObject.currentPosition.x, + y: floatingObject.currentPosition.y + } - var pos2 = { - x: payload.position.x, - y: payload.position.y - }; + var pos2 = { + x: payload.position.x, + y: payload.position.y + } - var posDiff = { // Next we need the vector resulting from the 2 positions. - x: pos2.x - pos1.x, - y: pos2.y - pos1.y - }; + var posDiff = { // Next we need the vector resulting from the 2 positions. + x: pos2.x - pos1.x, + y: pos2.y - pos1.y + } - var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector. - x: posDiff.x / d, - y: posDiff.y / d - }; + var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector. + x: posDiff.x / d, + y: posDiff.y / d + } - var forceVector = { - x: unitVector.x * force, - y: unitVector.y * force - }; + var forceVector = { + x: unitVector.x * force, + y: unitVector.y * force + } /* We add the force vector to the speed vector */ - floatingObject.currentSpeed.x = floatingObject.currentSpeed.x + forceVector.x; - floatingObject.currentSpeed.y = floatingObject.currentSpeed.y + forceVector.y; - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] gravityForce -> err.message = " + err.message); } - } + floatingObject.currentSpeed.x = floatingObject.currentSpeed.x + forceVector.x + floatingObject.currentSpeed.y = floatingObject.currentSpeed.y + forceVector.y + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] gravityForce -> err.message = ' + err.message) } } + } - function currentRepulsionForce(currentFloatingObject) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] currentRepulsionForce -> Entering function."); } + function currentRepulsionForce (currentFloatingObject) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] currentRepulsionForce -> Entering function.') } /* We generate a repulsion force between floatingObjects, that prevents them to be collisioning so often. */ - const coulomb = 2; + const coulomb = 2 - var floatingObject1 = visibleFloatingObjects[currentFloatingObject]; + var floatingObject1 = visibleFloatingObjects[currentFloatingObject] - for (var i = 0; i < visibleFloatingObjects.length; i++) { // The force to be applied is considering all other floatingObjects... + for (var i = 0; i < visibleFloatingObjects.length; i++) { + // The force to be applied is considering all other floatingObjects... - if (i !== currentFloatingObject) { // ... except for the current one. + if (i !== currentFloatingObject) { + // ... except for the current one. - var floatingObject2 = visibleFloatingObjects[i]; // So, for each floatingObject... + var floatingObject2 = visibleFloatingObjects[i] // So, for each floatingObject... - var d = Math.sqrt(Math.pow(floatingObject2.currentPosition.x - floatingObject1.currentPosition.x, 2) + Math.pow(floatingObject2.currentPosition.y - floatingObject1.currentPosition.y, 2)); // ... we calculate the distance ... + var d = Math.sqrt(Math.pow(floatingObject2.currentPosition.x - floatingObject1.currentPosition.x, 2) + Math.pow(floatingObject2.currentPosition.y - floatingObject1.currentPosition.y, 2)) // ... we calculate the distance ... - var force = coulomb * floatingObject2.currentMass / (d * d); // ... and with it the repulsion force. + var force = coulomb * floatingObject2.currentMass / (d * d) // ... and with it the repulsion force. /* We need to put a hard limit to this force, in order to to eject very little floatingObjects to the infinite and beyond. */ - if (force > 1) { - force = 1; - } + if (force > 1) { + force = 1 + } - var pos1 = { - x: floatingObject1.currentPosition.x, - y: floatingObject1.currentPosition.y - }; + var pos1 = { + x: floatingObject1.currentPosition.x, + y: floatingObject1.currentPosition.y + } - var pos2 = { - x: floatingObject2.currentPosition.x, - y: floatingObject2.currentPosition.y - }; + var pos2 = { + x: floatingObject2.currentPosition.x, + y: floatingObject2.currentPosition.y + } - var posDiff = { // Next we need the vector resulting from the 2 positions. - x: pos2.x - pos1.x, - y: pos2.y - pos1.y - }; + var posDiff = { // Next we need the vector resulting from the 2 positions. + x: pos2.x - pos1.x, + y: pos2.y - pos1.y + } - var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector. - x: posDiff.x / d, - y: posDiff.y / d - }; + var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector. + x: posDiff.x / d, + y: posDiff.y / d + } - var forceVector = { - x: unitVector.x * force, - y: unitVector.y * force - }; + var forceVector = { + x: unitVector.x * force, + y: unitVector.y * force + } /* We substract the force vector to the speed vector of the current floatingObject */ - floatingObject1.currentSpeed.x = floatingObject1.currentSpeed.x - forceVector.x; - floatingObject1.currentSpeed.y = floatingObject1.currentSpeed.y - forceVector.y; - - } - - } - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] currentRepulsionForce -> err.message = " + err.message); } + floatingObject1.currentSpeed.x = floatingObject1.currentSpeed.x - forceVector.x + floatingObject1.currentSpeed.y = floatingObject1.currentSpeed.y - forceVector.y } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] currentRepulsionForce -> err.message = ' + err.message) } } + } - function targetRepulsionForce(currentFloatingObject) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] targetRepulsionForce -> Entering function."); } + function targetRepulsionForce (currentFloatingObject) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] targetRepulsionForce -> Entering function.') } /* We generate a repulsion force between floatingObjects, that prevents them to be collisioning so often. */ - const coulomb = 2; + const coulomb = 2 - var floatingObject1 = visibleFloatingObjects[currentFloatingObject]; + var floatingObject1 = visibleFloatingObjects[currentFloatingObject] - for (var i = 0; i < visibleFloatingObjects.length; i++) { // The force to be applied is considering all other floatingObjects... + for (var i = 0; i < visibleFloatingObjects.length; i++) { + // The force to be applied is considering all other floatingObjects... - var floatingObject2 = visibleFloatingObjects[i]; // So, for each floatingObject... + var floatingObject2 = visibleFloatingObjects[i] // So, for each floatingObject... - let payload = { - position: undefined - }; + let payload = { + position: undefined + } - switch (floatingObject2.type) { + switch (floatingObject2.type) { - case "Profile Ball": { + case 'Profile Ball': { + payload.position = floatingObject2.payload.profile.position + break + } + case 'Note': { + payload.position = floatingObject2.payload.notes[floatingObject2.payloadNoteIndex].position + break + } + default: { + break + } + } - payload.position = floatingObject2.payload.profile.position; - break; - } - case "Note": { + var d = Math.sqrt(Math.pow(payload.position.x - floatingObject1.currentPosition.x, 2) + Math.pow(payload.position.y - floatingObject1.currentPosition.y, 2)) // ... we calculate the distance ... - payload.position = floatingObject2.payload.notes[floatingObject2.payloadNoteIndex].position; - break; - } - default: { - - break; - } - } - - var d = Math.sqrt(Math.pow(payload.position.x - floatingObject1.currentPosition.x, 2) + Math.pow(payload.position.y - floatingObject1.currentPosition.y, 2)); // ... we calculate the distance ... - - var force = coulomb * floatingObject2.currentMass / (d * d); // ... and with it the repulsion force. + var force = coulomb * floatingObject2.currentMass / (d * d) // ... and with it the repulsion force. /* We need to put a hard limit to this force, in order to to eject very little floatingObjects to the infinite and beyond. */ - if (force > maxTargetRepulsionForce) { - force = maxTargetRepulsionForce; - } + if (force > maxTargetRepulsionForce) { + force = maxTargetRepulsionForce + } - var pos1 = { - x: floatingObject1.currentPosition.x, - y: floatingObject1.currentPosition.y - }; + var pos1 = { + x: floatingObject1.currentPosition.x, + y: floatingObject1.currentPosition.y + } - var pos2 = { - x: payload.position.x, - y: payload.position.y - }; + var pos2 = { + x: payload.position.x, + y: payload.position.y + } - var posDiff = { // Next we need the vector resulting from the 2 positions. - x: pos2.x - pos1.x, - y: pos2.y - pos1.y - }; + var posDiff = { // Next we need the vector resulting from the 2 positions. + x: pos2.x - pos1.x, + y: pos2.y - pos1.y + } - var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector. - x: posDiff.x / d, - y: posDiff.y / d - }; + var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector. + x: posDiff.x / d, + y: posDiff.y / d + } - var forceVector = { - x: unitVector.x * force, - y: unitVector.y * force - }; + var forceVector = { + x: unitVector.x * force, + y: unitVector.y * force + } /* We substract the force vector to the speed vector of the current floatingObject */ - floatingObject1.currentSpeed.x = floatingObject1.currentSpeed.x - forceVector.x; - floatingObject1.currentSpeed.y = floatingObject1.currentSpeed.y - forceVector.y; - - } - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] targetRepulsionForce -> err.message = " + err.message); } - } + floatingObject1.currentSpeed.x = floatingObject1.currentSpeed.x - forceVector.x + floatingObject1.currentSpeed.y = floatingObject1.currentSpeed.y - forceVector.y + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] targetRepulsionForce -> err.message = ' + err.message) } } + } - function changeTargetRepulsion(pDelta) { + function changeTargetRepulsion (pDelta) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] changeTargetRepulsion -> Entering function.') } - try { + if (pDelta > 0) { + pDelta = 1 + } else { + pDelta = -1 + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] changeTargetRepulsion -> Entering function."); } + maxTargetRepulsionForce = maxTargetRepulsionForce + pDelta / 10000 - if (pDelta > 0) { - - pDelta = 1; - - } else { - - pDelta = -1; - - } - - maxTargetRepulsionForce = maxTargetRepulsionForce + pDelta / 10000; - - if (maxTargetRepulsionForce < 0.0001) { - - maxTargetRepulsionForce = 0.0001 - } - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] changeTargetRepulsion -> err.message = " + err.message); } - } + if (maxTargetRepulsionForce < 0.0001) { + maxTargetRepulsionForce = 0.0001 + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] changeTargetRepulsion -> err.message = ' + err.message) } } + } - function colliding(floatingObject1, floatingObject2) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] colliding -> Entering function."); } + function colliding (floatingObject1, floatingObject2) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] colliding -> Entering function.') } /* This function detects weather 2 floatingObjects collide with each other. */ - var r1 = floatingObject1.currentRadius; - var r2 = floatingObject2.currentRadius; + var r1 = floatingObject1.currentRadius + var r2 = floatingObject2.currentRadius - var distance = Math.sqrt(Math.pow(floatingObject2.currentPosition.x - floatingObject1.currentPosition.x, 2) + Math.pow(floatingObject2.currentPosition.y - floatingObject1.currentPosition.y, 2)); + var distance = Math.sqrt(Math.pow(floatingObject2.currentPosition.x - floatingObject1.currentPosition.x, 2) + Math.pow(floatingObject2.currentPosition.y - floatingObject1.currentPosition.y, 2)) - if (distance > (r1 + r2)) { - // No solutions, the circles are too far apart. - return false; - } - else if (distance <= r1 + r2) { + if (distance > (r1 + r2)) { + // No solutions, the circles are too far apart. + return false + } else if (distance <= r1 + r2) { // One circle contains the other. - return true; - } - else if ((distance === 0) && (r1 === r2)) { + return true + } else if ((distance === 0) && (r1 === r2)) { // the circles coincide. - return true; - } - else return true; - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] colliding -> err.message = " + err.message); } - } + return true + } else return true + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] colliding -> err.message = ' + err.message) } } + } - function isInside(x, y) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] isInside -> Entering function."); } + function isInside (x, y) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] isInside -> Entering function.') } /* This function detects weather the point x,y is inside any of the floatingObjects. */ - for (var i = 0; i < visibleFloatingObjects.length; i++) { - var floatingObject = visibleFloatingObjects[i]; - var distance = Math.sqrt(Math.pow(floatingObject.currentPosition.x - x, 2) + Math.pow(floatingObject.currentPosition.y - y, 2)); + for (var i = 0; i < visibleFloatingObjects.length; i++) { + var floatingObject = visibleFloatingObjects[i] + var distance = Math.sqrt(Math.pow(floatingObject.currentPosition.x - x, 2) + Math.pow(floatingObject.currentPosition.y - y, 2)) - if (distance < floatingObject.currentRadius) { - return i; - } - } - return -1; - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] isInside -> err.message = " + err.message); } + if (distance < floatingObject.currentRadius) { + return i } + } + return -1 + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] isInside -> err.message = ' + err.message) } } + } - function isInsideFloatingObject(floatingObjectIndex, x, y) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] isInsideFloatingObject -> Entering function."); } + function isInsideFloatingObject (floatingObjectIndex, x, y) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] isInsideFloatingObject -> Entering function.') } /* This function detects weather the point x,y is inside one particular floatingObjects. */ - var floatingObject = visibleFloatingObjects[floatingObjectIndex]; - var distance = Math.sqrt(Math.pow(floatingObject.currentPosition.x - x, 2) + Math.pow(floatingObject.currentPosition.y - y, 2)); + var floatingObject = visibleFloatingObjects[floatingObjectIndex] + var distance = Math.sqrt(Math.pow(floatingObject.currentPosition.x - x, 2) + Math.pow(floatingObject.currentPosition.y - y, 2)) - if (distance < floatingObject.currentRadius) { - return true; - } + if (distance < floatingObject.currentRadius) { + return true + } - return false; - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] isInsideFloatingObject -> err.message = " + err.message); } - } + return false + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] isInsideFloatingObject -> err.message = ' + err.message) } } + } - function distance(x1, y1, x2, y2) { + function distance (x1, y1, x2, y2) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] distance -> Entering function.') } - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] distance -> Entering function."); } - - return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] distance -> err.message = " + err.message); } - } + return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] distance -> err.message = ' + err.message) } } + } - function resolveCollision(floatingObject1, floatingObject2) { - - try { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] resolveCollision -> Entering function."); } + function resolveCollision (floatingObject1, floatingObject2) { + try { + if (INTENSIVE_LOG === true) { logger.write('[INFO] resolveCollision -> Entering function.') } /* This function changes speed and position of floatingObjects that are in collision */ - var collisionision_angle = Math.atan2((floatingObject2.currentPosition.y - floatingObject1.currentPosition.y), (floatingObject2.currentPosition.x - floatingObject1.currentPosition.x)); + var collisionision_angle = Math.atan2((floatingObject2.currentPosition.y - floatingObject1.currentPosition.y), (floatingObject2.currentPosition.x - floatingObject1.currentPosition.x)) - var speed1 = Math.sqrt(floatingObject1.currentSpeed.x * floatingObject1.currentSpeed.x + floatingObject1.currentSpeed.y * floatingObject1.currentSpeed.y); // Magnitude of Speed Vector for floatingObject 1 - var speed2 = Math.sqrt(floatingObject2.currentSpeed.x * floatingObject2.currentSpeed.x + floatingObject2.currentSpeed.y * floatingObject2.currentSpeed.y); // Magnitude of Speed Vector for floatingObject 2 + var speed1 = Math.sqrt(floatingObject1.currentSpeed.x * floatingObject1.currentSpeed.x + floatingObject1.currentSpeed.y * floatingObject1.currentSpeed.y) // Magnitude of Speed Vector for floatingObject 1 + var speed2 = Math.sqrt(floatingObject2.currentSpeed.x * floatingObject2.currentSpeed.x + floatingObject2.currentSpeed.y * floatingObject2.currentSpeed.y) // Magnitude of Speed Vector for floatingObject 2 - var direction_1 = Math.atan2(floatingObject1.currentSpeed.y, floatingObject1.currentSpeed.x); - var direction_2 = Math.atan2(floatingObject2.currentSpeed.y, floatingObject2.currentSpeed.x); + var direction_1 = Math.atan2(floatingObject1.currentSpeed.y, floatingObject1.currentSpeed.x) + var direction_2 = Math.atan2(floatingObject2.currentSpeed.y, floatingObject2.currentSpeed.x) - var new_xspeed_1 = speed1 * Math.cos(direction_1 - collisionision_angle); - var new_yspeed_1 = speed1 * Math.sin(direction_1 - collisionision_angle); - var new_xspeed_2 = speed2 * Math.cos(direction_2 - collisionision_angle); - var new_yspeed_2 = speed2 * Math.sin(direction_2 - collisionision_angle); + var new_xspeed_1 = speed1 * Math.cos(direction_1 - collisionision_angle) + var new_yspeed_1 = speed1 * Math.sin(direction_1 - collisionision_angle) + var new_xspeed_2 = speed2 * Math.cos(direction_2 - collisionision_angle) + var new_yspeed_2 = speed2 * Math.sin(direction_2 - collisionision_angle) - var final_xspeed_1 = ((floatingObject1.currentMass - floatingObject2.currentMass) * new_xspeed_1 + (floatingObject2.currentMass + floatingObject2.currentMass) * new_xspeed_2) / (floatingObject1.currentMass + floatingObject2.currentMass); - var final_xspeed_2 = ((floatingObject1.currentMass + floatingObject1.currentMass) * new_xspeed_1 + (floatingObject2.currentMass - floatingObject1.currentMass) * new_xspeed_2) / (floatingObject1.currentMass + floatingObject2.currentMass); - var final_yspeed_1 = new_yspeed_1; - var final_yspeed_2 = new_yspeed_2; + var final_xspeed_1 = ((floatingObject1.currentMass - floatingObject2.currentMass) * new_xspeed_1 + (floatingObject2.currentMass + floatingObject2.currentMass) * new_xspeed_2) / (floatingObject1.currentMass + floatingObject2.currentMass) + var final_xspeed_2 = ((floatingObject1.currentMass + floatingObject1.currentMass) * new_xspeed_1 + (floatingObject2.currentMass - floatingObject1.currentMass) * new_xspeed_2) / (floatingObject1.currentMass + floatingObject2.currentMass) + var final_yspeed_1 = new_yspeed_1 + var final_yspeed_2 = new_yspeed_2 - var cosAngle = Math.cos(collisionision_angle); - var sinAngle = Math.sin(collisionision_angle); + var cosAngle = Math.cos(collisionision_angle) + var sinAngle = Math.sin(collisionision_angle) - floatingObject1.currentSpeed.x = cosAngle * final_xspeed_1 - sinAngle * final_yspeed_1; - floatingObject1.currentSpeed.y = sinAngle * final_xspeed_1 + cosAngle * final_yspeed_1; + floatingObject1.currentSpeed.x = cosAngle * final_xspeed_1 - sinAngle * final_yspeed_1 + floatingObject1.currentSpeed.y = sinAngle * final_xspeed_1 + cosAngle * final_yspeed_1 - floatingObject2.currentSpeed.x = cosAngle * final_xspeed_2 - sinAngle * final_yspeed_2; - floatingObject2.currentSpeed.y = sinAngle * final_xspeed_2 + cosAngle * final_yspeed_2; + floatingObject2.currentSpeed.x = cosAngle * final_xspeed_2 - sinAngle * final_yspeed_2 + floatingObject2.currentSpeed.y = sinAngle * final_xspeed_2 + cosAngle * final_yspeed_2 - var pos1 = { - x: floatingObject1.currentPosition.x, - y: floatingObject1.currentPosition.y - }; + var pos1 = { + x: floatingObject1.currentPosition.x, + y: floatingObject1.currentPosition.y + } - var pos2 = { - x: floatingObject2.currentPosition.x, - y: floatingObject2.currentPosition.y - }; + var pos2 = { + x: floatingObject2.currentPosition.x, + y: floatingObject2.currentPosition.y + } // get the mtd - var posDiff = { - x: pos1.x - pos2.x, - y: pos1.y - pos2.y - }; + var posDiff = { + x: pos1.x - pos2.x, + y: pos1.y - pos2.y + } - var d = Math.sqrt(Math.pow(floatingObject2.currentPosition.x - floatingObject1.currentPosition.x, 2) + Math.pow(floatingObject2.currentPosition.y - floatingObject1.currentPosition.y, 2)); + var d = Math.sqrt(Math.pow(floatingObject2.currentPosition.x - floatingObject1.currentPosition.x, 2) + Math.pow(floatingObject2.currentPosition.y - floatingObject1.currentPosition.y, 2)) // minimum translation distance to push floatingObjects apart after intersecting - var scalar = (((floatingObject1.currentRadius + floatingObject2.currentRadius) - d) / d); + var scalar = (((floatingObject1.currentRadius + floatingObject2.currentRadius) - d) / d) - var minTD = { - x: posDiff.x * scalar, - y: posDiff.y * scalar - }; + var minTD = { + x: posDiff.x * scalar, + y: posDiff.y * scalar + } // resolve intersection -- // computing inverse mass quantities - var im1 = 1 / floatingObject1.currentMass; - var im2 = 1 / floatingObject2.currentMass; + var im1 = 1 / floatingObject1.currentMass + var im2 = 1 / floatingObject2.currentMass // push-pull them apart based off their mass - pos1.x = pos1.x + minTD.x * (im1 / (im1 + im2)); - pos1.y = pos1.y + minTD.y * (im1 / (im1 + im2)); - pos2.x = pos2.x - minTD.x * (im2 / (im1 + im2)); - pos2.y = pos2.y - minTD.y * (im2 / (im1 + im2)); + pos1.x = pos1.x + minTD.x * (im1 / (im1 + im2)) + pos1.y = pos1.y + minTD.y * (im1 / (im1 + im2)) + pos2.x = pos2.x - minTD.x * (im2 / (im1 + im2)) + pos2.y = pos2.y - minTD.y * (im2 / (im1 + im2)) - floatingObject1.currentPosition = pos1; - floatingObject2.currentPosition = pos2; - - } catch (err) { - if (ERROR_LOG === true) { logger.write("[ERROR] resolveCollision -> err.message = " + err.message); } - } + floatingObject1.currentPosition = pos1 + floatingObject2.currentPosition = pos2 + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] resolveCollision -> err.message = ' + err.message) } } + } } - diff --git a/FloatingSpace/FloatingObject.js b/FloatingSpace/FloatingObject.js index a3362e1ec..0d61a649d 100644 --- a/FloatingSpace/FloatingObject.js +++ b/FloatingSpace/FloatingObject.js @@ -1,274 +1,240 @@ - -function newFloatingObject() { +  +function newFloatingObject () { + const MODULE_NAME = 'Floating Object' + const INFO_LOG = false + const INTENSIVE_LOG = false + const ERROR_LOG = true - const MODULE_NAME = "Floating Object"; - const INFO_LOG = false; - const INTENSIVE_LOG = false; - const ERROR_LOG = true; + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + var thisObject = { - var thisObject = { + physicsLoop: physicsLoop, + eventHandler: undefined, - physicsLoop: physicsLoop, - eventHandler: undefined, + payload: undefined, // This is a reference to an object controlled by a Plotter. The plotter can change its internal value and we will see them from here. + type: undefined, // Currently there are two types of Floating Objects: Profile Balls, and Notes. - payload: undefined, // This is a reference to an object controlled by a Plotter. The plotter can change its internal value and we will see them from here. - type: undefined, // Currently there are two types of Floating Objects: Profile Balls, and Notes. + physicsEnabled: false, - physicsEnabled: false, + initializeMass: initializeMass, + initializeRadius: initializeRadius, + initializeImageSize: initializeImageSize, + initializeFontSize: initializeFontSize, - initializeMass: initializeMass, - initializeRadius: initializeRadius, - initializeImageSize: initializeImageSize, - initializeFontSize: initializeFontSize, + imageId: undefined, - imageId: undefined, + currentPosition: 0, // Current x,y position of the floating object at the floating object's layer, where there is no displacement or zoom. This position is always changing towards the target position. + currentSpeed: 0, // This is the current speed of the floating object. + currentRadius: 0, // This is the current radius of the floating object, including its zoom applied. + currentMass: 0, // This is the current mass of the floating object, including its zoom applied. - currentPosition: 0, // Current x,y position of the floating object at the floating object's layer, where there is no displacement or zoom. This position is always changing towards the target position. - currentSpeed: 0, // This is the current speed of the floating object. - currentRadius: 0, // This is the current radius of the floating object, including its zoom applied. - currentMass: 0, // This is the current mass of the floating object, including its zoom applied. + friction: 0, // This is a factor that will ultimatelly desacelerate the floating object. - friction: 0, // This is a factor that will ultimatelly desacelerate the floating object. + rawMass: 0, // This is the mass value without zoom. + rawRadius: 0, // This is the radius of this floating object without zoom. - rawMass: 0, // This is the mass value without zoom. - rawRadius: 0, // This is the radius of this floating object without zoom. + targetRadius: 0, // This is the target radius of the floating object with zoom applied. It should be animated until reaching this value. - targetRadius: 0, // This is the target radius of the floating object with zoom applied. It should be animated until reaching this value. + fillStyle: '', - fillStyle: '', + labelStrokeStyle: '', - labelStrokeStyle: '', + radomizeCurrentPosition: radomizeCurrentPosition, + radomizeCurrentSpeed: radomizeCurrentSpeed, - radomizeCurrentPosition: radomizeCurrentPosition, - radomizeCurrentSpeed: radomizeCurrentSpeed, + drawBackground: drawBackground, + drawForeground: drawForeground, - drawBackground: drawBackground, - drawForeground: drawForeground, + updateMass: updateMass, // Function to update the mass when the zoom level changed. + updateRadius: updateRadius, // Function to update the radius when the zoom level changed. - updateMass: updateMass, // Function to update the mass when the zoom level changed. - updateRadius: updateRadius, // Function to update the radius when the zoom level changed. + linkedObject: undefined, // This is a reference to the object that this floating object is representing. + linkedObjectType: '', // Since there might be floating objects for different types of objects, here we store the type of object we are linking to. - linkedObject: undefined, // This is a reference to the object that this floating object is representing. - linkedObjectType: "", // Since there might be floating objects for different types of objects, here we store the type of object we are linking to. + container: undefined, // This is a pointer to the object where the floating object belongs to. + initialize: initialize - container: undefined, // This is a pointer to the object where the floating object belongs to. - initialize: initialize + } - }; + let underlayingObject - let underlayingObject; + thisObject.eventHandler = newEventHandler() - thisObject.eventHandler = newEventHandler(); + return thisObject - return thisObject; + function initialize (pType, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } - function initialize(pType, callBackFunction) { + switch (pType) { - try { + case 'Profile Ball': { + underlayingObject = newProfileBall() + underlayingObject.initialize(onInitialized) - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function onInitialized (err) { - switch (pType) { + } - case "Profile Ball": { - - underlayingObject = newProfileBall(); - underlayingObject.initialize(onInitialized); - - function onInitialized(err) { - - - } - - break; - } - case "Note": { - - underlayingObject = newNote(); - underlayingObject.initialize(onInitialized); - - function onInitialized(err) { - - - } - break; - } - default: { - - break; - } - } - - thisObject.type = pType; - - thisObject.eventHandler.listenToEvent("onMouseOver", onMouseOver); - canvas.eventHandler.listenToEvent("onMouseNotOver", onMouseNotOver); - thisObject.eventHandler.listenToEvent("onMouseClick", onMouseClick); - - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } + break } - } + case 'Note': { + underlayingObject = newNote() + underlayingObject.initialize(onInitialized) - function physicsLoop(callBackFunction) { + function onInitialized (err) { - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - - underlayingObject.physicsLoop(); - - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] physicsLoop -> err.message = " + err.message); } - if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); } - } - } - - function onMouseOver() { - - thisObject.targetRadius = thisObject.rawRadius * 1.5; - thisObject.targetImageSize = thisObject.rawImageSize * 1.5; - thisObject.targetFontSize = thisObject.rawFontSize * 1.5; - - underlayingObject.onMouseOver(); - } - - function onMouseNotOver() { - - thisObject.targetRadius = thisObject.rawRadius * 1; - thisObject.targetImageSize = thisObject.rawImageSize * 1; - thisObject.targetFontSize = thisObject.rawFontSize * 1; - - underlayingObject.onMouseNotOver(); - } - - function onMouseClick(pPoint) { - - underlayingObject.onMouseClick(pPoint, thisObject); - - } - - function drawBackground() { - - underlayingObject.drawBackground(thisObject); - - } - - function drawForeground() { - - underlayingObject.drawForeground(thisObject); - - } - - function initializeMass(suggestedValue) { - - var mass = suggestedValue; - if (mass < 0.1) { - mass = 0.1; + } + break } - - thisObject.rawMass = mass; - thisObject.currentMass = mass; - - } - - function initializeRadius(suggestedValue) { - - var radius = suggestedValue; - if (radius < 2) { - radius = 2; + default: { + break } + } - thisObject.rawRadius = radius; - thisObject.targetRadius = radius; - thisObject.currentRadius = radius / 3; + thisObject.type = pType + thisObject.eventHandler.listenToEvent('onMouseOver', onMouseOver) + canvas.eventHandler.listenToEvent('onMouseNotOver', onMouseNotOver) + thisObject.eventHandler.listenToEvent('onMouseClick', onMouseClick) + + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } + + function physicsLoop (callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + + underlayingObject.physicsLoop() + + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] physicsLoop -> err.message = ' + err.message) } + if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } + + function onMouseOver () { + thisObject.targetRadius = thisObject.rawRadius * 1.5 + thisObject.targetImageSize = thisObject.rawImageSize * 1.5 + thisObject.targetFontSize = thisObject.rawFontSize * 1.5 + + underlayingObject.onMouseOver() + } + + function onMouseNotOver () { + thisObject.targetRadius = thisObject.rawRadius * 1 + thisObject.targetImageSize = thisObject.rawImageSize * 1 + thisObject.targetFontSize = thisObject.rawFontSize * 1 + + underlayingObject.onMouseNotOver() + } + + function onMouseClick (pPoint) { + underlayingObject.onMouseClick(pPoint, thisObject) + } + + function drawBackground () { + underlayingObject.drawBackground(thisObject) + } + + function drawForeground () { + underlayingObject.drawForeground(thisObject) + } + + function initializeMass (suggestedValue) { + var mass = suggestedValue + if (mass < 0.1) { + mass = 0.1 } - function initializeImageSize(suggestedValue) { - - var size = suggestedValue; - if (size < 2) { - size = 2; - } - - thisObject.rawImageSize = size; - thisObject.targetImageSize = size; - thisObject.currentImageSize = size / 3; + thisObject.rawMass = mass + thisObject.currentMass = mass + } + function initializeRadius (suggestedValue) { + var radius = suggestedValue + if (radius < 2) { + radius = 2 } - function initializeFontSize(suggestedValue) { - - var size = suggestedValue; - if (size < 3) { - size = 3; - } - - thisObject.rawFontSize = size; - thisObject.targetFontSize = size; - thisObject.currentFontSize = size / 3; + thisObject.rawRadius = radius + thisObject.targetRadius = radius + thisObject.currentRadius = radius / 3 + } + function initializeImageSize (suggestedValue) { + var size = suggestedValue + if (size < 2) { + size = 2 } - function radomizeCurrentPosition(arroundPoint) { + thisObject.rawImageSize = size + thisObject.targetImageSize = size + thisObject.currentImageSize = size / 3 + } - var position = { - x: Math.floor((Math.random() * (200) - 100)) + arroundPoint.x, - y: Math.floor((Math.random() * (200) - 100)) + arroundPoint.y - }; - - thisObject.currentPosition = position; + function initializeFontSize (suggestedValue) { + var size = suggestedValue + if (size < 3) { + size = 3 } - function radomizeCurrentSpeed() { + thisObject.rawFontSize = size + thisObject.targetFontSize = size + thisObject.currentFontSize = size / 3 + } - var initialXDirection; - var randomX = Math.floor((Math.random() * 10) + 1); - if (randomX > 5) { - initialXDirection = 1; - } else { - initialXDirection = - 1; - } - - var initialYDirection; - var randomY = Math.floor((Math.random() * 10) + 1); - if (randomY > 5) { - initialYDirection = 1; - } else { - initialYDirection = - 1; - } - - var velocity = { - x: initialXDirection * Math.floor((Math.random() * 300) + 1) / 100, - y: initialYDirection * Math.floor((Math.random() * 300) + 1) / 100 - }; - - thisObject.currentSpeed = velocity; + function radomizeCurrentPosition (arroundPoint) { + var position = { + x: Math.floor((Math.random() * (200) - 100)) + arroundPoint.x, + y: Math.floor((Math.random() * (200) - 100)) + arroundPoint.y } - function updateMass() { - - //thisObject.currentMass = thisObject.rawMass + thisObject.rawMass * thisObject.container.zoom.incrementM * thisObject.container.zoom.levelM; + thisObject.currentPosition = position + } + function radomizeCurrentSpeed () { + var initialXDirection + var randomX = Math.floor((Math.random() * 10) + 1) + if (randomX > 5) { + initialXDirection = 1 + } else { + initialXDirection = -1 } - function updateRadius() { - - //thisObject.targetRadius = thisObject.rawRadius + thisObject.rawRadius * thisObject.container.zoom.incrementR * thisObject.container.zoom.levelR; - + var initialYDirection + var randomY = Math.floor((Math.random() * 10) + 1) + if (randomY > 5) { + initialYDirection = 1 + } else { + initialYDirection = -1 } + + var velocity = { + x: initialXDirection * Math.floor((Math.random() * 300) + 1) / 100, + y: initialYDirection * Math.floor((Math.random() * 300) + 1) / 100 + } + + thisObject.currentSpeed = velocity + } + + function updateMass () { + + // thisObject.currentMass = thisObject.rawMass + thisObject.rawMass * thisObject.container.zoom.incrementM * thisObject.container.zoom.levelM; + + } + + function updateRadius () { + + // thisObject.targetRadius = thisObject.rawRadius + thisObject.rawRadius * thisObject.container.zoom.incrementR * thisObject.container.zoom.levelR; + + } } - - diff --git a/FloatingSpace/Note.js b/FloatingSpace/Note.js index 9916406b4..f1c5b8125 100644 --- a/FloatingSpace/Note.js +++ b/FloatingSpace/Note.js @@ -1,336 +1,304 @@ - -function newNote() { +  +function newNote () { + var thisObject = { - var thisObject = { + physicsLoop: physicsLoop, + onMouseOver: onMouseOver, + onMouseClick: onMouseClick, + onMouseNotOver: onMouseNotOver, + drawBackground: drawBackground, + drawForeground: drawForeground, + initialize: initialize - physicsLoop: physicsLoop, - onMouseOver: onMouseOver, - onMouseClick: onMouseClick, - onMouseNotOver: onMouseNotOver, - drawBackground: drawBackground, - drawForeground: drawForeground, - initialize: initialize + } - }; + return thisObject - return thisObject; + function initialize (callBackFunction) { + callBackFunction() + } - function initialize(callBackFunction) { + function physicsLoop () { - callBackFunction(); + } + function onMouseOver () { + + } + + function onMouseNotOver () { + + } + + function onMouseClick (pPoint, pFloatingObject) { + + } + + function drawBackground (pFloatingObject) { + let point = { + x: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.x, + y: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.y } - function physicsLoop() { - - } - - function onMouseOver() { - - } - - function onMouseNotOver() { - - } - - function onMouseClick(pPoint, pFloatingObject) { - - } - - function drawBackground(pFloatingObject) { - - let point = { - x: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.x, - y: pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].position.y - }; - - point = viewPort.fitIntoVisibleArea(point); - - if (pFloatingObject.currentRadius > 1) { + point = viewPort.fitIntoVisibleArea(point) + if (pFloatingObject.currentRadius > 1) { /* Target Line */ - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(pFloatingObject.currentPosition.x, pFloatingObject.currentPosition.y); - browserCanvasContext.lineTo(point.x, point.y); - browserCanvasContext.strokeStyle = 'rgba(204, 204, 204, 0.5)'; - browserCanvasContext.setLineDash([4, 2]); - browserCanvasContext.lineWidth = 1; - browserCanvasContext.stroke(); - browserCanvasContext.setLineDash([0, 0]); - - } - - if (pFloatingObject.currentRadius > 0.5) { - - /* Target Spot */ - - var radius = 1; - - browserCanvasContext.beginPath(); - browserCanvasContext.arc(point.x, point.y, radius, 0, Math.PI * 2, true); - browserCanvasContext.closePath(); - browserCanvasContext.fillStyle = 'rgba(30, 30, 30, 1)'; - browserCanvasContext.fill(); - - } + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(pFloatingObject.currentPosition.x, pFloatingObject.currentPosition.y) + browserCanvasContext.lineTo(point.x, point.y) + browserCanvasContext.strokeStyle = 'rgba(204, 204, 204, 0.5)' + browserCanvasContext.setLineDash([4, 2]) + browserCanvasContext.lineWidth = 1 + browserCanvasContext.stroke() + browserCanvasContext.setLineDash([0, 0]) } - function drawForeground(pFloatingObject) { + if (pFloatingObject.currentRadius > 0.5) { + /* Target Spot */ - const BUBBLE_CORNERS_RADIOUS = 5; - const TITLE_BAR_HEIGHT = 14; + var radius = 1 - const BUBBLE_WIDTH = BUBBLE_CORNERS_RADIOUS + pFloatingObject.currentRadius * 4; - const BUBBLE_HEIGHT = BUBBLE_CORNERS_RADIOUS + pFloatingObject.currentRadius * 2; + browserCanvasContext.beginPath() + browserCanvasContext.arc(point.x, point.y, radius, 0, Math.PI * 2, true) + browserCanvasContext.closePath() + browserCanvasContext.fillStyle = 'rgba(30, 30, 30, 1)' + browserCanvasContext.fill() + } + } - let borderPoint1; - let borderPoint2; - let borderPoint3; - let borderPoint4; + function drawForeground (pFloatingObject) { + const BUBBLE_CORNERS_RADIOUS = 5 + const TITLE_BAR_HEIGHT = 14 - let intialDisplace = { - x: pFloatingObject.currentPosition.x - BUBBLE_WIDTH / 2, - y: pFloatingObject.currentPosition.y - BUBBLE_HEIGHT / 2 - } + const BUBBLE_WIDTH = BUBBLE_CORNERS_RADIOUS + pFloatingObject.currentRadius * 4 + const BUBBLE_HEIGHT = BUBBLE_CORNERS_RADIOUS + pFloatingObject.currentRadius * 2 - if (pFloatingObject.currentRadius > 5) { + let borderPoint1 + let borderPoint2 + let borderPoint3 + let borderPoint4 + let intialDisplace = { + x: pFloatingObject.currentPosition.x - BUBBLE_WIDTH / 2, + y: pFloatingObject.currentPosition.y - BUBBLE_HEIGHT / 2 + } + + if (pFloatingObject.currentRadius > 5) { /* Rounded Background */ - borderPoint1 = { - x: intialDisplace.x + BUBBLE_CORNERS_RADIOUS, - y: intialDisplace.y + BUBBLE_CORNERS_RADIOUS - }; + borderPoint1 = { + x: intialDisplace.x + BUBBLE_CORNERS_RADIOUS, + y: intialDisplace.y + BUBBLE_CORNERS_RADIOUS + } - borderPoint2 = { - x: intialDisplace.x + BUBBLE_WIDTH - BUBBLE_CORNERS_RADIOUS, - y: intialDisplace.y + BUBBLE_CORNERS_RADIOUS - }; + borderPoint2 = { + x: intialDisplace.x + BUBBLE_WIDTH - BUBBLE_CORNERS_RADIOUS, + y: intialDisplace.y + BUBBLE_CORNERS_RADIOUS + } - borderPoint3 = { - x: intialDisplace.x + BUBBLE_WIDTH - BUBBLE_CORNERS_RADIOUS, - y: intialDisplace.y + BUBBLE_HEIGHT - BUBBLE_CORNERS_RADIOUS - }; + borderPoint3 = { + x: intialDisplace.x + BUBBLE_WIDTH - BUBBLE_CORNERS_RADIOUS, + y: intialDisplace.y + BUBBLE_HEIGHT - BUBBLE_CORNERS_RADIOUS + } - borderPoint4 = { - x: intialDisplace.x + BUBBLE_CORNERS_RADIOUS, - y: intialDisplace.y + + BUBBLE_HEIGHT - BUBBLE_CORNERS_RADIOUS - }; + borderPoint4 = { + x: intialDisplace.x + BUBBLE_CORNERS_RADIOUS, + y: intialDisplace.y + +BUBBLE_HEIGHT - BUBBLE_CORNERS_RADIOUS + } - titleBarPoint1 = { - x: intialDisplace.x + 0, - y: intialDisplace.y + TITLE_BAR_HEIGHT - }; + titleBarPoint1 = { + x: intialDisplace.x + 0, + y: intialDisplace.y + TITLE_BAR_HEIGHT + } - titleBarPoint2 = { - x: intialDisplace.x + BUBBLE_WIDTH, - y: intialDisplace.y + TITLE_BAR_HEIGHT - }; + titleBarPoint2 = { + x: intialDisplace.x + BUBBLE_WIDTH, + y: intialDisplace.y + TITLE_BAR_HEIGHT + } /* We paint the panel background first */ - browserCanvasContext.fillStyle = 'rgba(255, 249, 196, 0.75)'; - browserCanvasContext.beginPath(); + browserCanvasContext.fillStyle = 'rgba(255, 249, 196, 0.75)' + browserCanvasContext.beginPath() - browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, BUBBLE_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI); - browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - BUBBLE_CORNERS_RADIOUS); - browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, BUBBLE_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI); - browserCanvasContext.lineTo(borderPoint3.x + BUBBLE_CORNERS_RADIOUS, borderPoint3.y); - browserCanvasContext.arc(borderPoint3.x, borderPoint3.y, BUBBLE_CORNERS_RADIOUS, 0 * Math.PI, 0.5 * Math.PI); - browserCanvasContext.lineTo(borderPoint4.x, borderPoint4.y + BUBBLE_CORNERS_RADIOUS); - browserCanvasContext.arc(borderPoint4.x, borderPoint4.y, BUBBLE_CORNERS_RADIOUS, 0.5 * Math.PI, 1.0 * Math.PI); - browserCanvasContext.lineTo(borderPoint1.x - BUBBLE_CORNERS_RADIOUS, borderPoint1.y); + browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, BUBBLE_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI) + browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - BUBBLE_CORNERS_RADIOUS) + browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, BUBBLE_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI) + browserCanvasContext.lineTo(borderPoint3.x + BUBBLE_CORNERS_RADIOUS, borderPoint3.y) + browserCanvasContext.arc(borderPoint3.x, borderPoint3.y, BUBBLE_CORNERS_RADIOUS, 0 * Math.PI, 0.5 * Math.PI) + browserCanvasContext.lineTo(borderPoint4.x, borderPoint4.y + BUBBLE_CORNERS_RADIOUS) + browserCanvasContext.arc(borderPoint4.x, borderPoint4.y, BUBBLE_CORNERS_RADIOUS, 0.5 * Math.PI, 1.0 * Math.PI) + browserCanvasContext.lineTo(borderPoint1.x - BUBBLE_CORNERS_RADIOUS, borderPoint1.y) - browserCanvasContext.closePath(); + browserCanvasContext.closePath() - browserCanvasContext.fill(); + browserCanvasContext.fill() - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.75)'; - browserCanvasContext.stroke(); + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.75)' + browserCanvasContext.stroke() /* We paint the title bar now */ - browserCanvasContext.fillStyle = 'rgba(244, 224, 44, 0.75)'; - browserCanvasContext.beginPath(); + browserCanvasContext.fillStyle = 'rgba(244, 224, 44, 0.75)' + browserCanvasContext.beginPath() - browserCanvasContext.moveTo(titleBarPoint1.x, titleBarPoint1.y); - browserCanvasContext.lineTo(borderPoint1.x - BUBBLE_CORNERS_RADIOUS, borderPoint1.y); - browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, BUBBLE_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI); - browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - BUBBLE_CORNERS_RADIOUS); - browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, BUBBLE_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI); - browserCanvasContext.lineTo(titleBarPoint2.x, titleBarPoint2.y); + browserCanvasContext.moveTo(titleBarPoint1.x, titleBarPoint1.y) + browserCanvasContext.lineTo(borderPoint1.x - BUBBLE_CORNERS_RADIOUS, borderPoint1.y) + browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, BUBBLE_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI) + browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - BUBBLE_CORNERS_RADIOUS) + browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, BUBBLE_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI) + browserCanvasContext.lineTo(titleBarPoint2.x, titleBarPoint2.y) - browserCanvasContext.closePath(); - browserCanvasContext.fill(); + browserCanvasContext.closePath() + browserCanvasContext.fill() - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', 0.75)'; - browserCanvasContext.stroke(); - - } - - if (pFloatingObject.currentRadius > 0.5) { + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', 0.75)' + browserCanvasContext.stroke() + } + if (pFloatingObject.currentRadius > 0.5) { /* Image */ - let imagePosition = { - x: pFloatingObject.currentPosition.x, - y: pFloatingObject.currentPosition.y + BUBBLE_HEIGHT / 2 - }; + let imagePosition = { + x: pFloatingObject.currentPosition.x, + y: pFloatingObject.currentPosition.y + BUBBLE_HEIGHT / 2 + } - if (pFloatingObject.payloadImageId !== undefined) { + if (pFloatingObject.payloadImageId !== undefined) { + let image = document.getElementById(pFloatingObject.payloadImageId) - let image = document.getElementById(pFloatingObject.payloadImageId); - - if (image !== null) { - - browserCanvasContext.drawImage(image, imagePosition.x - pFloatingObject.currentImageSize / 2, imagePosition.y - pFloatingObject.currentImageSize / 2, pFloatingObject.currentImageSize, pFloatingObject.currentImageSize); - - } - } + if (image !== null) { + browserCanvasContext.drawImage(image, imagePosition.x - pFloatingObject.currentImageSize / 2, imagePosition.y - pFloatingObject.currentImageSize / 2, pFloatingObject.currentImageSize, pFloatingObject.currentImageSize) + } + } /* Image Contourn */ - browserCanvasContext.beginPath(); - browserCanvasContext.arc(imagePosition.x, imagePosition.y, pFloatingObject.currentImageSize / 2, 0, Math.PI * 2, true); - browserCanvasContext.closePath(); - browserCanvasContext.strokeStyle = 'rgba(30, 30, 30, 0.25)'; - browserCanvasContext.lineWidth = 1; - browserCanvasContext.stroke(); + browserCanvasContext.beginPath() + browserCanvasContext.arc(imagePosition.x, imagePosition.y, pFloatingObject.currentImageSize / 2, 0, Math.PI * 2, true) + browserCanvasContext.closePath() + browserCanvasContext.strokeStyle = 'rgba(30, 30, 30, 0.25)' + browserCanvasContext.lineWidth = 1 + browserCanvasContext.stroke() /* Labels */ - if (pFloatingObject.currentRadius > 6) { + if (pFloatingObject.currentRadius > 6) { + browserCanvasContext.strokeStyle = pFloatingObject.labelStrokeStyle - browserCanvasContext.strokeStyle = pFloatingObject.labelStrokeStyle; + const SIZE_PERCENTAGE = Math.trunc(pFloatingObject.currentRadius / pFloatingObject.targetRadius * 100) / 100 + let ALPHA - const SIZE_PERCENTAGE = Math.trunc(pFloatingObject.currentRadius / pFloatingObject.targetRadius * 100) / 100; - let ALPHA; + if (pFloatingObject.targetRadius > 0) { + ALPHA = 0.5 - (1 - SIZE_PERCENTAGE) * 5 + } else { + // Object is dying... - if (pFloatingObject.targetRadius > 0) { + ALPHA = Math.trunc((0.5 - (100 - pFloatingObject.currentRadius / 100)) * 100) / 100 - ALPHA = 0.5 - (1 - SIZE_PERCENTAGE) * 5; + if (ALPHA < 0) { ALPHA = 0 } + } - } else { // Object is dying... + let labelPoint + let fontSize = 10 - ALPHA = Math.trunc((0.5 - (100 - pFloatingObject.currentRadius / 100) ) * 100) / 100; - - if (ALPHA < 0) { ALPHA = 0} - - } - - let labelPoint; - let fontSize = 10; - - let label; + let label /* print the title */ - label = pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].title; + label = pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].title - if (label !== undefined) { + if (label !== undefined) { + if (SIZE_PERCENTAGE > 0.9) { + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY - if (SIZE_PERCENTAGE > 0.9) { + let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO + let yOffset = (TITLE_BAR_HEIGHT - fontSize) / 2 + 2 - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; + labelPoint = { + x: intialDisplace.x + BUBBLE_WIDTH / 2 - xOffset, + y: intialDisplace.y + TITLE_BAR_HEIGHT - yOffset + } - let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO; - let yOffset = (TITLE_BAR_HEIGHT - fontSize) / 2 + 2; - - labelPoint = { - x: intialDisplace.x + BUBBLE_WIDTH / 2 - xOffset, - y: intialDisplace.y + TITLE_BAR_HEIGHT - yOffset - }; - - browserCanvasContext.fillStyle = 'rgba(30, 30, 30, ' + ALPHA + ')' - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); - - } - } + browserCanvasContext.fillStyle = 'rgba(30, 30, 30, ' + ALPHA + ')' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + } + } /* Message Body */ - label = pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].body; + label = pFloatingObject.payload.notes[pFloatingObject.payloadNoteIndex].body - if (label !== undefined) { + if (label !== undefined) { + const WORDS_PER_ROW = 5 + const TOTAL_ROWS = 5 - const WORDS_PER_ROW = 5; - const TOTAL_ROWS = 5; - - if (SIZE_PERCENTAGE > 0.9) { - - let rawLabelArray = label.split(" "); - let labelArray = []; + if (SIZE_PERCENTAGE > 0.9) { + let rawLabelArray = label.split(' ') + let labelArray = [] /* Lets check when words are to long we add an empty space to the same line so as to roll all other words forward. */ - for (let i = 0; i < rawLabelArray.length; i++) { + for (let i = 0; i < rawLabelArray.length; i++) { + let word = rawLabelArray[i] - let word = rawLabelArray[i]; + labelArray.push(word) - labelArray.push(word); + if (word.length > 8) { + labelArray.push('') + } - if (word.length > 8) { - labelArray.push(""); - } - - if (word.length > 10) { - labelArray.push(""); - } - } + if (word.length > 10) { + labelArray.push('') + } + } /* Calculate each ROW */ - let labelRows = []; + let labelRows = [] - for (let i = 0; i < TOTAL_ROWS; i++) { + for (let i = 0; i < TOTAL_ROWS; i++) { + let labelRow = '' - let labelRow = ""; + for (let j = 0; j < WORDS_PER_ROW; j++) { + let newWord = labelArray[j + i * WORDS_PER_ROW] - for (let j = 0; j < WORDS_PER_ROW; j++) { + if (newWord !== undefined && newWord !== '') { + labelRow = labelRow + ' ' + newWord + } + } - let newWord = labelArray[j + i * WORDS_PER_ROW]; - - if (newWord !== undefined && newWord !== "") { - - labelRow = labelRow + " " + newWord; - } - } - - if (labelRow !== "") { - - labelRows.push(labelRow); - - } - - } + if (labelRow !== '') { + labelRows.push(labelRow) + } + } /* Now we plot each row. */ - for (let i = 0; i < labelRows.length; i++) { + for (let i = 0; i < labelRows.length; i++) { + let labelRow = labelRows[i] - let labelRow = labelRows[i]; + let startingPosition = { + x: pFloatingObject.currentPosition.x, + y: pFloatingObject.currentPosition.y - labelRows.length / 2 * (fontSize * FONT_ASPECT_RATIO + 10) + } - let startingPosition = { - x: pFloatingObject.currentPosition.x, - y: pFloatingObject.currentPosition.y - labelRows.length / 2 * (fontSize * FONT_ASPECT_RATIO + 10) - }; + labelPoint = { + x: startingPosition.x - labelRow.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: startingPosition.y + (i + 1) * (fontSize * FONT_ASPECT_RATIO + 10) + } - labelPoint = { - x: startingPosition.x - labelRow.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: startingPosition.y + (i + 1) * (fontSize * FONT_ASPECT_RATIO + 10) - }; - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, ' + ALPHA + ')' - browserCanvasContext.fillText(labelRow, labelPoint.x, labelPoint.y); - - } - } - } + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, ' + ALPHA + ')' + browserCanvasContext.fillText(labelRow, labelPoint.x, labelPoint.y) } + } } + } } + } } diff --git a/FloatingSpace/NoteSets.js b/FloatingSpace/NoteSets.js index 5339bdf90..b1e8c42fd 100644 --- a/FloatingSpace/NoteSets.js +++ b/FloatingSpace/NoteSets.js @@ -1,6 +1,5 @@ - -function newNoteSets() { - +  +function newNoteSets () { /* Different plotters will identify sets of notes whithin the data they are plotting. They will create with them arrays of Notes data. On the other hand the floating space, and a floting layer in particular, manages Notes floating objects, which are visible entities @@ -14,48 +13,43 @@ function newNoteSets() { This module is capable of managing an array of NoteSets. */ - const MODULE_NAME = "Note Sets"; - const INFO_LOG = false; - const INFO_WARN = true; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + const MODULE_NAME = 'Note Sets' + const INFO_LOG = false + const INFO_WARN = true + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - let thisObject = { - createNoteSet: createNoteSet, - destroyNoteSet: destroyNoteSet, - initialize: initialize - }; + let thisObject = { + createNoteSet: createNoteSet, + destroyNoteSet: destroyNoteSet, + initialize: initialize + } - let noteSets = []; - let floatingLayer; + let noteSets = [] + let floatingLayer - return thisObject; - - function initialize(pFloatingLayer, callBackFunction) { + return thisObject + function initialize (pFloatingLayer, callBackFunction) { /* During the initialization process, we receive the floatingLayer where all the floatingObjects we will be creating here will live at. */ - try { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + floatingLayer = pFloatingLayer - floatingLayer = pFloatingLayer; - - callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function createNoteSet(pPayload, pEventHandler, callBackFunction) { - - try { + function createNoteSet (pPayload, pEventHandler, callBackFunction) { + try { /* During the creating of a NoteSet, no floating objects are created yet. What we do here is to create the data structure which will allocate the Notes floating objects, once we receive the array of notes raw data from the plotter. This array will come as an event raised by the @@ -63,41 +57,39 @@ function newNoteSets() { position the user gives to the viewport, but also, the plotter can be receiving actually new notes from its datasource. */ - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> Entering function."); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> Entering function.') } - let noteSet = { - imageId: pPayload.profile.imageId, - floatingNotes: [], - payload: pPayload, - handle: Math.floor((Math.random() * 10000000) + 1) - }; + let noteSet = { + imageId: pPayload.profile.imageId, + floatingNotes: [], + payload: pPayload, + handle: Math.floor((Math.random() * 10000000) + 1) + } - noteSets.push(noteSet); + noteSets.push(noteSet) - pEventHandler.listenToEvent("Notes Changed", onNotesChanged, noteSets.length - 1) + pEventHandler.listenToEvent('Notes Changed', onNotesChanged, noteSets.length - 1) - callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE, noteSet.handle); + callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE, noteSet.handle) - function onNotesChanged(pNewNotes, pNoteSetIndex) { + function onNotesChanged (pNewNotes, pNoteSetIndex) { + try { + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> pNewNotes.length = ' + pNewNotes.length) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> pNoteSetIndex = ' + pNoteSetIndex) } - try { + let noteSet = noteSets[pNoteSetIndex] + let found = false + let newFloatingNotes - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> pNewNotes.length = " + pNewNotes.length); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> pNoteSetIndex = " + pNoteSetIndex); } - - let noteSet = noteSets[pNoteSetIndex]; - let found = false; - let newFloatingNotes; - - /* + /* First we remove the old notes. This means that we are going to scan all the floating objects that we have, and see one by one if they are still present on the raw data sent by the plotter. If it is not there, that means that the floating object must be discarded. */ - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes."); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes.') } - newFloatingNotes = []; // We will create a new array of Floating Notes as a result of this operation. + newFloatingNotes = [] // We will create a new array of Floating Notes as a result of this operation. /* Here we scan the curren array of floating objects. We use the date + rate to create a unique key for each one, in order to be able to @@ -105,171 +97,156 @@ function newNoteSets() { that are still at the raw data array to a new array, and not adding the ones that are not. */ - for (let j = 0; j < noteSet.floatingNotes.length; j++) { + for (let j = 0; j < noteSet.floatingNotes.length; j++) { + found = false - found = false; + let floatingNote = noteSet.floatingNotes[j] + let floatingNoteKey = floatingNote.date.toString() + floatingNote.rate.toString() - let floatingNote = noteSet.floatingNotes[j]; - let floatingNoteKey = floatingNote.date.toString() + floatingNote.rate.toString(); + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> j = ' + j) } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> j = " + j); } + let i - let i; + for (i = 0; i < pNewNotes.length; i++) { + let plotterNote = pNewNotes[i] + let plotterNoteKey = plotterNote.date.toString() + plotterNote.rate.toString() - for (i = 0; i < pNewNotes.length; i++) { + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> i = ' + i) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNoteKey = ' + floatingNoteKey) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> plotterNoteKey = ' + plotterNoteKey) } - let plotterNote = pNewNotes[i]; - let plotterNoteKey = plotterNote.date.toString() + plotterNote.rate.toString(); + if (plotterNoteKey === floatingNoteKey) { + found = true - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> i = " + i); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNoteKey = " + floatingNoteKey); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> plotterNoteKey = " + plotterNoteKey); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> found = ' + found) } + break + } + } - if (plotterNoteKey === floatingNoteKey) { - - found = true; - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> found = " + found); } - break; - } - } - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> End of For i."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> found = " + found); } - - if (found === false) { + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> End of For i.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> found = ' + found) } + if (found === false) { /* Each time we identify a floatingObject that is not at the raw data anymore, we request the floatinglayer to kill it. */ - floatingLayer.killFloatingObject(floatingNote.floatingHandle, onObjectKilled); + floatingLayer.killFloatingObject(floatingNote.floatingHandle, onObjectKilled) - function onObjectKilled(err) { + function onObjectKilled (err) { + if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + if (ERROR_LOG === true) { logger.write('[ERROR] createNoteSet -> onNotesChanged -> Remove old Notes -> Floating Object Not Found.') } + if (ERROR_LOG === true) { logger.write('[ERROR] createNoteSet -> onNotesChanged -> Remove old Notes -> Floating Object cannot be killed.') } + if (ERROR_LOG === true) { logger.write('[ERROR] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNote.floatingHandle = ' + floatingNote.floatingHandle) } + return + } - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNote.floatingHandle = ' + floatingNote.floatingHandle) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> Removed from Layer.') } + } + } else { + newFloatingNotes.push(floatingNote) - if (ERROR_LOG === true) { logger.write("[ERROR] createNoteSet -> onNotesChanged -> Remove old Notes -> Floating Object Not Found."); } - if (ERROR_LOG === true) { logger.write("[ERROR] createNoteSet -> onNotesChanged -> Remove old Notes -> Floating Object cannot be killed."); } - if (ERROR_LOG === true) { logger.write("[ERROR] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNote.floatingHandle = " + floatingNote.floatingHandle); } - return; - } - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNote.floatingHandle = " + floatingNote.floatingHandle); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> Removed from Layer."); } - } - - } else { - - newFloatingNotes.push(floatingNote); - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNote.floatingHandle = " + floatingNote.floatingHandle); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> Added to newFloatingNotes."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> newFloatingNotes.length = " + newFloatingNotes.length); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingNote.floatingHandle = ' + floatingNote.floatingHandle) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> Added to newFloatingNotes.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> newFloatingNotes.length = ' + newFloatingNotes.length) } /* We set a property at each floatingObject of which is the index of the note at the raw data array, so that it can later evaluate its position or its visibility. */ - let floatingObject = floatingLayer.getFloatingObject(floatingNote.floatingHandle); - floatingObject.payloadNoteIndex = i; + let floatingObject = floatingLayer.getFloatingObject(floatingNote.floatingHandle) + floatingObject.payloadNoteIndex = i - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingObject index updated."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingObject.payloadNoteIndex = " + i); } - - } - } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingObject index updated.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> floatingObject.payloadNoteIndex = ' + i) } + } + } /* We replace the current array, with the new one that only contains the surviving floating objects, meaning the ones that are still at the raw data received. */ - noteSet.floatingNotes = newFloatingNotes; + noteSet.floatingNotes = newFloatingNotes - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> noteSet.floatingNotes.length = " + noteSet.floatingNotes.length); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Remove old Notes -> noteSet.floatingNotes.length = ' + noteSet.floatingNotes.length) } - /* + /* Second we add the new notes. There might be new notes at the raw data received that we didnt have before at the NodeSet array. To figure out which ones are, we need to scan the raw data array and compare each element with the ones of the NodeSet array. Whenever we find one that is not there, we add it. */ - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes."); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes.') } - newFloatingNotes = []; // We will create a new array of Floating Notes as a result of this operation. + newFloatingNotes = [] // We will create a new array of Floating Notes as a result of this operation. /* We are using the date and rate as a unique key to identify each note. To prevent the cases of duplicate keys, we will check that at least to consecutive records dont have the same key, and if they do, will ignore the second one. */ - let lastPlotterKey = ""; + let lastPlotterKey = '' - for (let i = 0; i < pNewNotes.length; i++) { + for (let i = 0; i < pNewNotes.length; i++) { + found = false - found = false; + let plotterNote = pNewNotes[i] + let plotterNoteKey = plotterNote.date.toString() + plotterNote.rate.toString() + let floatingNote + let floatingNoteKey - let plotterNote = pNewNotes[i]; - let plotterNoteKey = plotterNote.date.toString() + plotterNote.rate.toString(); - let floatingNote; - let floatingNoteKey; + if (lastPlotterKey === plotterNoteKey) { + if (INFO_WARN === true) { logger.write('[WARN] createNoteSet -> onNotesChanged -> Add new Notes -> Duplicate record detected. Discarding it.') } + if (INFO_WARN === true) { logger.write('[WARN] createNoteSet -> onNotesChanged -> Add new Notes -> i = ' + i) } + continue + } - if (lastPlotterKey === plotterNoteKey) { + lastPlotterKey = plotterNoteKey - if (INFO_WARN=== true) { logger.write("[WARN] createNoteSet -> onNotesChanged -> Add new Notes -> Duplicate record detected. Discarding it."); } - if (INFO_WARN === true) { logger.write("[WARN] createNoteSet -> onNotesChanged -> Add new Notes -> i = " + i); } - continue; - } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> i = ' + i) } - lastPlotterKey = plotterNoteKey; + for (let j = 0; j < noteSet.floatingNotes.length; j++) { + floatingNote = noteSet.floatingNotes[j] + floatingNoteKey = floatingNote.date.toString() + floatingNote.rate.toString() - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> i = " + i); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> j = ' + j) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> floatingNoteKey = ' + floatingNoteKey) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> plotterNoteKey = ' + plotterNoteKey) } - for (let j = 0; j < noteSet.floatingNotes.length; j++) { + if (plotterNoteKey === floatingNoteKey) { + found = true - floatingNote = noteSet.floatingNotes[j]; - floatingNoteKey = floatingNote.date.toString() + floatingNote.rate.toString(); + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> found = ' + found) } + break + } + } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> j = " + j); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> floatingNoteKey = " + floatingNoteKey); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> plotterNoteKey = " + plotterNoteKey); } - - if (plotterNoteKey === floatingNoteKey) { - - found = true; - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> found = " + found); } - break; - } - } - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> End of For j."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> found = " + found); } - - if (found === false) { + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> End of For j.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> found = ' + found) } + if (found === false) { /* Before adding a new item to the array, we need to create a floatingObject of type Note. Once we set its basic parameters we can it to our array and to the floating layer. */ - let floatingObject = newFloatingObject(); - floatingObject.initialize("Note", onInitialized); + let floatingObject = newFloatingObject() + floatingObject.initialize('Note', onInitialized) - function onInitialized(err) { + function onInitialized (err) { + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Entering function."); } + floatingObject.payload = noteSet.payload + floatingObject.payloadNoteIndex = i + floatingObject.payloadImageId = noteSet.imageId - floatingObject.payload = noteSet.payload; - floatingObject.payloadNoteIndex = i; - floatingObject.payloadImageId = noteSet.imageId; + floatingObject.friction = 0.995 - floatingObject.friction = .995; + floatingObject.initializeMass(200) - floatingObject.initializeMass(200); - - //let bodyText = pNewNotes[i].body; - let radius; + // let bodyText = pNewNotes[i].body; + let radius /* if (bodyText.length < 100) { @@ -278,96 +255,83 @@ function newNoteSets() { radius = bodyText.length; } */ - radius = 50; + radius = 50 - floatingObject.initializeRadius(radius); - floatingObject.initializeImageSize(15); + floatingObject.initializeRadius(radius) + floatingObject.initializeImageSize(15) - floatingObject.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.5)'; - floatingObject.labelStrokeStyle = 'rgba(60, 60, 60, 0.50)'; + floatingObject.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.5)' + floatingObject.labelStrokeStyle = 'rgba(60, 60, 60, 0.50)' - floatingLayer.addFloatingObject(floatingObject); + floatingLayer.addFloatingObject(floatingObject) - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> New Note added to Layer."); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> New Note added to Layer.') } - plotterNote.floatingHandle = floatingObject.handle; + plotterNote.floatingHandle = floatingObject.handle - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> plotterNote.floatingHandle = " + plotterNote.floatingHandle); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> plotterNote.floatingHandle = ' + plotterNote.floatingHandle) } - newFloatingNotes.push(plotterNote); + newFloatingNotes.push(plotterNote) - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Added to newFloatingNotes."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> newFloatingNotes.length = " + newFloatingNotes.length); } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Added to newFloatingNotes.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> newFloatingNotes.length = ' + newFloatingNotes.length) } + } + } else { + newFloatingNotes.push(floatingNote) - } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Old Note Kept.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> floatingNote.floatingHandle = ' + floatingNote.floatingHandle) } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Added to newFloatingNotes.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> newFloatingNotes.length = ' + newFloatingNotes.length) } - } else { + let floatingObject = floatingLayer.getFloatingObject(floatingNote.floatingHandle) + floatingObject.payloadNoteIndex = i - newFloatingNotes.push(floatingNote); - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Old Note Kept."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> floatingNote.floatingHandle = " + floatingNote.floatingHandle); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> Added to newFloatingNotes."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> newFloatingNotes.length = " + newFloatingNotes.length); } - - let floatingObject = floatingLayer.getFloatingObject(floatingNote.floatingHandle); - floatingObject.payloadNoteIndex = i; - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> floatingObject index updated."); } - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> floatingObject.payloadNoteIndex = " + i); } - - } - } - - noteSet.floatingNotes = newFloatingNotes; - - if (INFO_LOG === true) { logger.write("[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> noteSet.floatingNotes.length = " + noteSet.floatingNotes.length); } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] createNoteSet -> onNotesChanged -> err = " + err); } - } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> floatingObject index updated.') } + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> onInitialized -> floatingObject.payloadNoteIndex = ' + i) } } + } + + noteSet.floatingNotes = newFloatingNotes + + if (INFO_LOG === true) { logger.write('[INFO] createNoteSet -> onNotesChanged -> Add new Notes -> noteSet.floatingNotes.length = ' + noteSet.floatingNotes.length) } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] createNoteSet -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] createNoteSet -> onNotesChanged -> err = ' + err) } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] createNoteSet -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function destroyNoteSet(pHandle) { - - try { + function destroyNoteSet (pHandle) { + try { /* Usually when a bot is disabled by the end user, or the zoom level changes to one where the notes must not be seen, this method to destroy an entire NoteSet is executed. What we do in this situation is to localize the NoteSet to be destroyed and we need to kill, one by one the floating objects in it. Finally we remove this NoteSet item from the NoteSets array. */ - if (INFO_LOG === true) { logger.write("[INFO] destroyNoteSet -> Entering function."); } + if (INFO_LOG === true) { logger.write('[INFO] destroyNoteSet -> Entering function.') } - for (let i = 0; i < noteSets.length; i++) { + for (let i = 0; i < noteSets.length; i++) { + let noteSet = noteSets[i] - let noteSet = noteSets[i]; + if (noteSet.handle === pHandle) { + for (let j = 0; j < noteSet.floatingNotes.length; j++) { + let floatingNote = noteSet.floatingNotes[j] - if (noteSet.handle === pHandle) { + floatingLayer.killFloatingObject(floatingNote.floatingHandle) + } - for (let j = 0; j < noteSet.floatingNotes.length; j++) { - - let floatingNote = noteSet.floatingNotes[j]; - - floatingLayer.killFloatingObject(floatingNote.floatingHandle); - } - - noteSets.splice(i, 1); // Delete item from array. - return; - } - } - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] destroyNoteSet -> err = " + err); } + noteSets.splice(i, 1) // Delete item from array. + return } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] destroyNoteSet -> err = ' + err) } } + } } - diff --git a/FloatingSpace/ProfileBall.js b/FloatingSpace/ProfileBall.js index a8fd8dd6f..23f60d563 100644 --- a/FloatingSpace/ProfileBall.js +++ b/FloatingSpace/ProfileBall.js @@ -310,4 +310,3 @@ function newProfileBall () { } } } - diff --git a/FloatingSpace/ProfileBalls.js b/FloatingSpace/ProfileBalls.js index 5c1aa0126..7f0d90750 100644 --- a/FloatingSpace/ProfileBalls.js +++ b/FloatingSpace/ProfileBalls.js @@ -1,11 +1,10 @@ - -function newProfileBalls() { - - const MODULE_NAME = "Profile Balls"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; +  +function newProfileBalls () { + const MODULE_NAME = 'Profile Balls' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME /* @@ -13,65 +12,56 @@ function newProfileBalls() { */ - let thisObject = { + let thisObject = { - createNewProfileBall: createNewProfileBall, - destroyProfileBall: destroyProfileBall, - initialize: initialize + createNewProfileBall: createNewProfileBall, + destroyProfileBall: destroyProfileBall, + initialize: initialize + } + + let floatingLayer + + return thisObject + + function initialize (pFloatingLayer, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + + floatingLayer = pFloatingLayer + + callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - let floatingLayer; + function createNewProfileBall (pPayload, callBackFunction) { + let floatingObject = newFloatingObject() + floatingObject.initialize('Profile Ball', onInitialized) - return thisObject; + function onInitialized (err) { + floatingObject.payload = pPayload - function initialize(pFloatingLayer, callBackFunction) { + floatingObject.friction = 0.995 - try { + floatingObject.initializeMass(100) + floatingObject.initializeRadius(30) + floatingObject.initializeImageSize(50) + floatingObject.initializeFontSize(10) - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + floatingObject.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.5)' + floatingObject.labelStrokeStyle = 'rgba(60, 60, 60, 0.50)' - floatingLayer = pFloatingLayer; + floatingLayer.addFloatingObject(floatingObject) - callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE, floatingObject.handle) } + } - function createNewProfileBall(pPayload, callBackFunction) { - - let floatingObject = newFloatingObject(); - floatingObject.initialize("Profile Ball", onInitialized); - - function onInitialized(err) { - - floatingObject.payload = pPayload; - - floatingObject.friction = .995; - - floatingObject.initializeMass(100); - floatingObject.initializeRadius(30); - floatingObject.initializeImageSize(50); - floatingObject.initializeFontSize(10); - - floatingObject.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.5)'; - floatingObject.labelStrokeStyle = 'rgba(60, 60, 60, 0.50)'; - - floatingLayer.addFloatingObject(floatingObject); - - callBackFunction(GLOBAL.CUSTOM_OK_RESPONSE, floatingObject.handle); - - } - } - - function destroyProfileBall(pFloatingObjectHandle) { - - floatingLayer.killFloatingObject(pFloatingObjectHandle); - - } + function destroyProfileBall (pFloatingObjectHandle) { + floatingLayer.killFloatingObject(pFloatingObjectHandle) + } } diff --git a/Frame.js b/Frame.js index 3d52d5435..062c55a3d 100644 --- a/Frame.js +++ b/Frame.js @@ -1,130 +1,110 @@ - -function newFrame() { +  +function newFrame () { + const PANEL_CORNERS_RADIOUS = 5 + const TITLE_BAR_HEIGHT = 14 // this must be grater than radius - const PANEL_CORNERS_RADIOUS = 5; - const TITLE_BAR_HEIGHT = 14; // this must be grater than radius + var frame = { + containerName: '', // This is for debugging purposes only. + parentFrame: undefined, // Here we store the parent cointainer zoom object. + width: browserCanvas.width, + height: browserCanvas.height, + position: undefined, + getBodyHeight: getBodyHeight, + draw: draw, + container: undefined, + frameThisPoint: frameThisPoint, // This function changes the actual frame coordinate system to the screen coordinate system. + unframeThisPoint: unframeThisPoint, + fitIntoFrame: fitIntoFrame, + isThisPointHere: isThisPointHere, // This function return true is the point received as parameter lives within this frame. + isInViewPort: isInViewPort, + canYouMoveHere: canYouMoveHere, + canYouZoomHere: canYouZoomHere, + initialize: initialize + } - var frame = { - containerName: "", // This is for debugging purposes only. - parentFrame: undefined, // Here we store the parent cointainer zoom object. - width: browserCanvas.width, - height: browserCanvas.height, - position: undefined, - getBodyHeight: getBodyHeight, - draw: draw, - container: undefined, - frameThisPoint: frameThisPoint, // This function changes the actual frame coordinate system to the screen coordinate system. - unframeThisPoint: unframeThisPoint, - fitIntoFrame: fitIntoFrame, - isThisPointHere: isThisPointHere, // This function return true is the point received as parameter lives within this frame. - isInViewPort: isInViewPort, - canYouMoveHere: canYouMoveHere, - canYouZoomHere: canYouZoomHere, - initialize: initialize - }; + return frame - return frame; - - function initialize() { - - var position = { - x: 0, - y: 0 - }; - - this.position = position; + function initialize () { + var position = { + x: 0, + y: 0 } + this.position = position + } - function getBodyHeight() { - - return frame.height - TITLE_BAR_HEIGHT; + function getBodyHeight () { + return frame.height - TITLE_BAR_HEIGHT + } + function isInViewPort () { + point1 = { + x: 0, + y: 0 } - function isInViewPort() { - - point1 = { - x: 0, - y: 0 - }; - - point3 = { - x: frame.width, - y: frame.height - }; - + point3 = { + x: frame.width, + y: frame.height + } /* Now the transformations. */ - point1 = transformThisPoint(point1, frame.container); - point3 = transformThisPoint(point3, frame.container); - - if (point1.x < viewPort.visibleArea.topRight.x && point1.y < viewPort.visibleArea.bottomRight.y && point3.x > viewPort.visibleArea.bottomLeft.x && point3.y > viewPort.visibleArea.topLeft.y ) { - - return true; - } else { - return false; - } + point1 = transformThisPoint(point1, frame.container) + point3 = transformThisPoint(point3, frame.container) + if (point1.x < viewPort.visibleArea.topRight.x && point1.y < viewPort.visibleArea.bottomRight.y && point3.x > viewPort.visibleArea.bottomLeft.x && point3.y > viewPort.visibleArea.topLeft.y) { + return true + } else { + return false } + } - function fitIntoFrame(point) { - - + function fitIntoFrame (point) { /* Here we check the boundaries of the resulting points, so they dont go out of the visible area. */ - if (point.x > frame.width) { - point.x = frame.width; - } - - if (point.x < 0) { - point.x = 0; - } - - if (point.y > frame.height) { - point.y = frame.height; - } - - if (point.y < 0) { - point.y = 0; - } - - return point; + if (point.x > frame.width) { + point.x = frame.width } - - - function frameThisPoint(point) { - - if (this.parentFrame !== undefined) { - - point = this.parentFrame.frameThisPoint(point); - - } - - point.x = point.x + frame.position.x; - point.y = point.y + frame.position.y; - - return point; + if (point.x < 0) { + point.x = 0 } - function unframeThisPoint(point) { - - if (this.parentFrame !== undefined) { - - point = this.parentFrame.unframeThisPoint(point); - - } - - point.x = point.x - this.position.x; - point.y = point.y - this.position.y; - - return point; + if (point.y > frame.height) { + point.y = frame.height } - function canYouMoveHere(tempDisplacement) { + if (point.y < 0) { + point.y = 0 + } + return point + } + + function frameThisPoint (point) { + if (this.parentFrame !== undefined) { + point = this.parentFrame.frameThisPoint(point) + } + + point.x = point.x + frame.position.x + point.y = point.y + frame.position.y + + return point + } + + function unframeThisPoint (point) { + if (this.parentFrame !== undefined) { + point = this.parentFrame.unframeThisPoint(point) + } + + point.x = point.x - this.position.x + point.y = point.y - this.position.y + + return point + } + + function canYouMoveHere (tempDisplacement) { /* The current frame has a position and a displacement. We need to check that none of the boundaries points of the frame fall outside of its container frame. @@ -132,459 +112,427 @@ function newFrame() { */ - point1 = { - x: this.position.x, - y: this.position.y - }; + point1 = { + x: this.position.x, + y: this.position.y + } - point2 = { - x: this.position.x + this.width, - y: this.position.y - }; + point2 = { + x: this.position.x + this.width, + y: this.position.y + } - point3 = { - x: this.position.x + this.width, - y: this.position.y + this.height - }; + point3 = { + x: this.position.x + this.width, + y: this.position.y + this.height + } - point4 = { - x: this.position.x, - y: this.position.y + this.height - }; + point4 = { + x: this.position.x, + y: this.position.y + this.height + } /* Now the transformations. */ - if (this.parentFrame !== undefined) { // If there is not a parent then there is no point to check bounderies. + if (this.parentFrame !== undefined) { + // If there is not a parent then there is no point to check bounderies. - point1 = this.parentFrame.frameThisPoint(point1); - point2 = this.parentFrame.frameThisPoint(point2); - point3 = this.parentFrame.frameThisPoint(point3); - point4 = this.parentFrame.frameThisPoint(point4); + point1 = this.parentFrame.frameThisPoint(point1) + point2 = this.parentFrame.frameThisPoint(point2) + point3 = this.parentFrame.frameThisPoint(point3) + point4 = this.parentFrame.frameThisPoint(point4) /* We apply the temporary displacement. */ - point1 = tempDisplacement.displaceThisPoint(point1); - point2 = tempDisplacement.displaceThisPoint(point2); - point3 = tempDisplacement.displaceThisPoint(point3); - point4 = tempDisplacement.displaceThisPoint(point4); + point1 = tempDisplacement.displaceThisPoint(point1) + point2 = tempDisplacement.displaceThisPoint(point2) + point3 = tempDisplacement.displaceThisPoint(point3) + point4 = tempDisplacement.displaceThisPoint(point4) /* We add the actual displacement. */ - point1 = this.container.displacement.displaceThisPoint(point1); - point2 = this.container.displacement.displaceThisPoint(point2); - point3 = this.container.displacement.displaceThisPoint(point3); - point4 = this.container.displacement.displaceThisPoint(point4); + point1 = this.container.displacement.displaceThisPoint(point1) + point2 = this.container.displacement.displaceThisPoint(point2) + point3 = this.container.displacement.displaceThisPoint(point3) + point4 = this.container.displacement.displaceThisPoint(point4) - if (this.parentFrame.isThisPointHere(point1) === false) { - return false; - } + if (this.parentFrame.isThisPointHere(point1) === false) { + return false + } - if (this.parentFrame.isThisPointHere(point2) === false) { - return false; - } + if (this.parentFrame.isThisPointHere(point2) === false) { + return false + } - if (this.parentFrame.isThisPointHere(point3) === false) { - return false; - } + if (this.parentFrame.isThisPointHere(point3) === false) { + return false + } - if (this.parentFrame.isThisPointHere(point4) === false) { - return false; - } - - } - - return true; + if (this.parentFrame.isThisPointHere(point4) === false) { + return false + } } - function canYouZoomHere(tempZoom) { + return true + } - point1 = { - x: this.position.x, - y: this.position.y - }; + function canYouZoomHere (tempZoom) { + point1 = { + x: this.position.x, + y: this.position.y + } - point2 = { - x: this.position.x + this.width, - y: this.position.y - }; + point2 = { + x: this.position.x + this.width, + y: this.position.y + } - point3 = { - x: this.position.x + this.width, - y: this.position.y + this.height - }; + point3 = { + x: this.position.x + this.width, + y: this.position.y + this.height + } - point4 = { - x: this.position.x, - y: this.position.y + this.height - }; + point4 = { + x: this.position.x, + y: this.position.y + this.height + } /* Now the transformations. */ - if (this.parentFrame !== undefined) { // If there is not a parent then there is no point to check bounderies. + if (this.parentFrame !== undefined) { + // If there is not a parent then there is no point to check bounderies. - point1 = this.parentFrame.frameThisPoint(point1); - point2 = this.parentFrame.frameThisPoint(point2); - point3 = this.parentFrame.frameThisPoint(point3); - point4 = this.parentFrame.frameThisPoint(point4); + point1 = this.parentFrame.frameThisPoint(point1) + point2 = this.parentFrame.frameThisPoint(point2) + point3 = this.parentFrame.frameThisPoint(point3) + point4 = this.parentFrame.frameThisPoint(point4) /* We add the actual displacement. */ - point1 = this.container.displacement.displaceThisPoint(point1); - point2 = this.container.displacement.displaceThisPoint(point2); - point3 = this.container.displacement.displaceThisPoint(point3); - point4 = this.container.displacement.displaceThisPoint(point4); + point1 = this.container.displacement.displaceThisPoint(point1) + point2 = this.container.displacement.displaceThisPoint(point2) + point3 = this.container.displacement.displaceThisPoint(point3) + point4 = this.container.displacement.displaceThisPoint(point4) /* We temp zoom. */ - point1 = tempZoom.zoomThisPoint(point1); - point2 = tempZoom.zoomThisPoint(point2); - point3 = tempZoom.zoomThisPoint(point3); - point4 = tempZoom.zoomThisPoint(point4); + point1 = tempZoom.zoomThisPoint(point1) + point2 = tempZoom.zoomThisPoint(point2) + point3 = tempZoom.zoomThisPoint(point3) + point4 = tempZoom.zoomThisPoint(point4) - if (this.parentFrame.isThisPointHere(point1) === false) { - return false; - } + if (this.parentFrame.isThisPointHere(point1) === false) { + return false + } - if (this.parentFrame.isThisPointHere(point2) === false) { - return false; - } + if (this.parentFrame.isThisPointHere(point2) === false) { + return false + } - if (this.parentFrame.isThisPointHere(point3) === false) { - return false; - } + if (this.parentFrame.isThisPointHere(point3) === false) { + return false + } - if (this.parentFrame.isThisPointHere(point4) === false) { - return false; - } - - } - - return true; + if (this.parentFrame.isThisPointHere(point4) === false) { + return false + } } + return true + } - function isThisPointHere(point, outsideViewPort) { // The second parameter is usefull when you want to check a point that you already know is outside the viewport. + function isThisPointHere (point, outsideViewPort) { + // The second parameter is usefull when you want to check a point that you already know is outside the viewport. /* We need not to modify the point received, so me make a copy of it. */ - var checkPoint = { - x: point.x, - y: point.y - }; + var checkPoint = { + x: point.x, + y: point.y + } /* The point received is on the screen coordinates system, which already has zoom and displacement applied. We need to remove the zoom and displacement in order to have the point on the containers coordinate system and be able to compare it with its dimmensions. */ - if (outsideViewPort === true) { - - checkPoint = this.container.displacement.undisplaceThisPoint(checkPoint); - checkPoint = this.container.frame.unframeThisPoint(checkPoint); - - } else { - checkPoint = unTransformThisPoint(checkPoint, frame.container); - } + if (outsideViewPort === true) { + checkPoint = this.container.displacement.undisplaceThisPoint(checkPoint) + checkPoint = this.container.frame.unframeThisPoint(checkPoint) + } else { + checkPoint = unTransformThisPoint(checkPoint, frame.container) + } /* Now we check if the resulting point is whin the current Frame. */ - if (checkPoint.x < 0 || checkPoint.y < 0 || checkPoint.x > frame.width || checkPoint.y > frame.height) { - + if (checkPoint.x < 0 || checkPoint.y < 0 || checkPoint.x > frame.width || checkPoint.y > frame.height) { /* The point received is not in this frame */ - return false; - - } else { - + return false + } else { /* The point is within this frame. */ - return true; - - } + return true + } + } + function draw (drawGrid, drawBorders, drawBackground) { + if (drawBorders === true) { + borders() } - function draw(drawGrid, drawBorders, drawBackground) { - - - if (drawBorders === true) { - borders(); - } - - if (drawGrid === true) { - grid(); - } - - if (drawBackground === true) { - background(); - } + if (drawGrid === true) { + grid() } - function background() { + if (drawBackground === true) { + background() + } + } + function background () { + borderPoint1 = { + x: PANEL_CORNERS_RADIOUS, + y: PANEL_CORNERS_RADIOUS + } + borderPoint2 = { + x: frame.width - PANEL_CORNERS_RADIOUS, + y: PANEL_CORNERS_RADIOUS + } - borderPoint1 = { - x: PANEL_CORNERS_RADIOUS, - y: PANEL_CORNERS_RADIOUS - }; + borderPoint3 = { + x: frame.width - PANEL_CORNERS_RADIOUS, + y: frame.height - PANEL_CORNERS_RADIOUS + } - borderPoint2 = { - x: frame.width - PANEL_CORNERS_RADIOUS, - y: PANEL_CORNERS_RADIOUS - }; + borderPoint4 = { + x: PANEL_CORNERS_RADIOUS, + y: frame.height - PANEL_CORNERS_RADIOUS + } - borderPoint3 = { - x: frame.width - PANEL_CORNERS_RADIOUS, - y: frame.height - PANEL_CORNERS_RADIOUS - }; - - borderPoint4 = { - x: PANEL_CORNERS_RADIOUS, - y: frame.height - PANEL_CORNERS_RADIOUS - }; - - titleBarPoint1 = { - x: 0, - y: TITLE_BAR_HEIGHT - }; - - titleBarPoint2 = { - x: frame.width, - y: TITLE_BAR_HEIGHT - }; + titleBarPoint1 = { + x: 0, + y: TITLE_BAR_HEIGHT + } + titleBarPoint2 = { + x: frame.width, + y: TITLE_BAR_HEIGHT + } /* Now the transformations. */ - borderPoint1 = frameThisPoint(borderPoint1); - borderPoint2 = frameThisPoint(borderPoint2); - borderPoint3 = frameThisPoint(borderPoint3); - borderPoint4 = frameThisPoint(borderPoint4); + borderPoint1 = frameThisPoint(borderPoint1) + borderPoint2 = frameThisPoint(borderPoint2) + borderPoint3 = frameThisPoint(borderPoint3) + borderPoint4 = frameThisPoint(borderPoint4) - titleBarPoint1 = frameThisPoint(titleBarPoint1); - titleBarPoint2 = frameThisPoint(titleBarPoint2); + titleBarPoint1 = frameThisPoint(titleBarPoint1) + titleBarPoint2 = frameThisPoint(titleBarPoint2) /* We paint the panel background first */ - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.75)'; - browserCanvasContext.beginPath(); + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.75)' + browserCanvasContext.beginPath() - browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, PANEL_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI); - browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - PANEL_CORNERS_RADIOUS); - browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, PANEL_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI); - browserCanvasContext.lineTo(borderPoint3.x + PANEL_CORNERS_RADIOUS, borderPoint3.y); - browserCanvasContext.arc(borderPoint3.x, borderPoint3.y, PANEL_CORNERS_RADIOUS, 0 * Math.PI, 0.5 * Math.PI); - browserCanvasContext.lineTo(borderPoint4.x, borderPoint4.y + PANEL_CORNERS_RADIOUS); - browserCanvasContext.arc(borderPoint4.x, borderPoint4.y, PANEL_CORNERS_RADIOUS, 0.5 * Math.PI, 1.0 * Math.PI); - browserCanvasContext.lineTo(borderPoint1.x - PANEL_CORNERS_RADIOUS, borderPoint1.y); + browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, PANEL_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI) + browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - PANEL_CORNERS_RADIOUS) + browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, PANEL_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI) + browserCanvasContext.lineTo(borderPoint3.x + PANEL_CORNERS_RADIOUS, borderPoint3.y) + browserCanvasContext.arc(borderPoint3.x, borderPoint3.y, PANEL_CORNERS_RADIOUS, 0 * Math.PI, 0.5 * Math.PI) + browserCanvasContext.lineTo(borderPoint4.x, borderPoint4.y + PANEL_CORNERS_RADIOUS) + browserCanvasContext.arc(borderPoint4.x, borderPoint4.y, PANEL_CORNERS_RADIOUS, 0.5 * Math.PI, 1.0 * Math.PI) + browserCanvasContext.lineTo(borderPoint1.x - PANEL_CORNERS_RADIOUS, borderPoint1.y) - browserCanvasContext.closePath(); + browserCanvasContext.closePath() - browserCanvasContext.fill(); + browserCanvasContext.fill() - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.MANGANESE_PURPLE + ', 0.75)'; - browserCanvasContext.stroke(); - - + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.MANGANESE_PURPLE + ', 0.75)' + browserCanvasContext.stroke() /* We paint the title bar now */ - - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', 0.75)'; - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(titleBarPoint1.x, titleBarPoint1.y); - browserCanvasContext.lineTo(borderPoint1.x - PANEL_CORNERS_RADIOUS, borderPoint1.y); - browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, PANEL_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI); - browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - PANEL_CORNERS_RADIOUS); - browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, PANEL_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI); - browserCanvasContext.lineTo(titleBarPoint2.x, titleBarPoint2.y); + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', 0.75)' + browserCanvasContext.beginPath() - browserCanvasContext.closePath(); - browserCanvasContext.fill(); - - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.MANGANESE_PURPLE + ', 0.75)'; - browserCanvasContext.stroke(); + browserCanvasContext.moveTo(titleBarPoint1.x, titleBarPoint1.y) + browserCanvasContext.lineTo(borderPoint1.x - PANEL_CORNERS_RADIOUS, borderPoint1.y) + browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, PANEL_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI) + browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - PANEL_CORNERS_RADIOUS) + browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, PANEL_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI) + browserCanvasContext.lineTo(titleBarPoint2.x, titleBarPoint2.y) + + browserCanvasContext.closePath() + browserCanvasContext.fill() + + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.MANGANESE_PURPLE + ', 0.75)' + browserCanvasContext.stroke() /* print the title */ - let labelPoint; - let fontSize = 10; + let labelPoint + let fontSize = 10 - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY - let label = frame.containerName; + let label = frame.containerName - let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO; - let yOffset = (TITLE_BAR_HEIGHT - fontSize) / 2 + 2; + let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO + let yOffset = (TITLE_BAR_HEIGHT - fontSize) / 2 + 2 - labelPoint = { - x: frame.width / 2 - xOffset, - y: TITLE_BAR_HEIGHT - yOffset - }; - - labelPoint = frame.frameThisPoint(labelPoint); - - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + labelPoint = { + x: frame.width / 2 - xOffset, + y: TITLE_BAR_HEIGHT - yOffset } + labelPoint = frame.frameThisPoint(labelPoint) - function borders() { - + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + } + function borders () { /* Lest get the important points of the drawing so as to apply the needed transformations. */ - point1 = { - x: 0, - y: 0 - }; + point1 = { + x: 0, + y: 0 + } - point2 = { - x: frame.width, - y: 0 - }; + point2 = { + x: frame.width, + y: 0 + } - point3 = { - x: frame.width, - y: frame.height - }; + point3 = { + x: frame.width, + y: frame.height + } - point4 = { - x: 0, - y: frame.height - }; + point4 = { + x: 0, + y: frame.height + } /* Now the transformations. */ - point1 = transformThisPoint(point1, frame.container); - point2 = transformThisPoint(point2, frame.container); - point3 = transformThisPoint(point3, frame.container); - point4 = transformThisPoint(point4, frame.container); + point1 = transformThisPoint(point1, frame.container) + point2 = transformThisPoint(point2, frame.container) + point3 = transformThisPoint(point3, frame.container) + point4 = transformThisPoint(point4, frame.container) /* Lets start the drawing. */ - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - browserCanvasContext.lineTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - browserCanvasContext.lineTo(point1.x, point1.y); - browserCanvasContext.closePath(); + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + browserCanvasContext.lineTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + browserCanvasContext.lineTo(point1.x, point1.y) + browserCanvasContext.closePath() + browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)' + browserCanvasContext.lineWidth = 1 + browserCanvasContext.stroke() - browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)'; - browserCanvasContext.lineWidth = 1; - browserCanvasContext.stroke(); - - browserCanvasContext.closePath(); - - - - } - - - - function grid(smallLines) { - - if (smallLines === true) { + browserCanvasContext.closePath() + } + function grid (smallLines) { + if (smallLines === true) { /* Small Lines */ - var step = frame.width / 100; + var step = frame.width / 100 - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - for (var i = 0; i < frame.width; i = i + step) { + for (var i = 0; i < frame.width; i = i + step) { + for (var j = 0; j < frame.height; j = j + step) { + let point1 = { + x: 0, + y: j + } - for (var j = 0; j < frame.height; j = j + step) { + let point2 = { + x: frame.width, + y: j + } - let point1 = { - x: 0, - y: j - }; + point1 = transformThisPoint(point1, frame.container) + point2 = transformThisPoint(point2, frame.container) - let point2 = { - x: frame.width, - y: j - }; - - point1 = transformThisPoint(point1, frame.container); - point2 = transformThisPoint(point2, frame.container); - - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - } - - let point3 = { - x: frame.width, - y: frame.height - }; - - let point4 = { - x: 0, - y: frame.height - }; - - point3 = transformThisPoint(point3, frame.container); - point4 = transformThisPoint(point4, frame.container); - - browserCanvasContext.moveTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - } - browserCanvasContext.closePath(); - browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.1)'; - browserCanvasContext.lineWidth = 1; - browserCanvasContext.stroke(); + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) } + let point3 = { + x: frame.width, + y: frame.height + } + + let point4 = { + x: 0, + y: frame.height + } + + point3 = transformThisPoint(point3, frame.container) + point4 = transformThisPoint(point4, frame.container) + + browserCanvasContext.moveTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + } + browserCanvasContext.closePath() + browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.1)' + browserCanvasContext.lineWidth = 1 + browserCanvasContext.stroke() + } /* Main Lines */ - var step = frame.width / 20; + var step = frame.width / 20 - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - for (var i = 0; i < frame.width; i = i + step) { - - for (var j = 0; j < frame.height; j = j + step) { - - let point1 = { - x: 0, - y: j - }; - - let point2 = { - x: frame.width, - y: j - }; - - point1 = transformThisPoint(point1, frame.container); - point2 = transformThisPoint(point2, frame.container); - - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - } - - let point3 = { - x: i, - y: 0 - }; - - let point4 = { - x: i, - y: frame.height - }; - - point3 = transformThisPoint(point3, frame.container); - point4 = transformThisPoint(point4, frame.container); - - browserCanvasContext.moveTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); + for (var i = 0; i < frame.width; i = i + step) { + for (var j = 0; j < frame.height; j = j + step) { + let point1 = { + x: 0, + y: j } - browserCanvasContext.closePath(); - browserCanvasContext.strokeStyle = 'rgba(100, 100, 100, 0.2)'; - browserCanvasContext.lineWidth = 1; - browserCanvasContext.stroke(); + + let point2 = { + x: frame.width, + y: j + } + + point1 = transformThisPoint(point1, frame.container) + point2 = transformThisPoint(point2, frame.container) + + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + } + + let point3 = { + x: i, + y: 0 + } + + let point4 = { + x: i, + y: frame.height + } + + point3 = transformThisPoint(point3, frame.container) + point4 = transformThisPoint(point4, frame.container) + + browserCanvasContext.moveTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) } -} \ No newline at end of file + browserCanvasContext.closePath() + browserCanvasContext.strokeStyle = 'rgba(100, 100, 100, 0.2)' + browserCanvasContext.lineWidth = 1 + browserCanvasContext.stroke() + } +} diff --git a/Globals.js b/Globals.js index 29efabfb0..ae3b813cc 100644 --- a/Globals.js +++ b/Globals.js @@ -1,4 +1,4 @@ -/* User Interface Colors */ + /* User Interface Colors */ UI_COLOR = { DARK: "48, 48, 54", diff --git a/Panels/ProductsPanel.js b/Panels/ProductsPanel.js index 004fb7b05..856d276c8 100644 --- a/Panels/ProductsPanel.js +++ b/Panels/ProductsPanel.js @@ -1,240 +1,210 @@ -function newProductsPanel() { - - var thisObject = { - container: undefined, - getLoadingProductCards: getLoadingProductCards, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + function newProductsPanel () { + var thisObject = { + container: undefined, + getLoadingProductCards: getLoadingProductCards, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } /* Cointainer stuff */ - var container = newContainer(); + var container = newContainer() - container.name = "Indicators and Algobots Product Panel"; - container.initialize(); + container.name = 'Indicators and Algobots Product Panel' + container.initialize() - container.isDraggeable = true; - container.isWheelable = true; + container.isDraggeable = true + container.isWheelable = true - thisObject.container = container; - thisObject.container.frame.containerName = "Indicators and Algobots's Products"; + thisObject.container = container + thisObject.container.frame.containerName = "Indicators and Algobots's Products" - let isInitialized = false; - let productCards = []; + let isInitialized = false + let productCards = [] - let visibleProductCards = []; - let firstVisibleCard = 1; + let visibleProductCards = [] + let firstVisibleCard = 1 /* Needed Variables */ - var lastY = 5; + var lastY = 5 - return thisObject; + return thisObject - function initialize() { + function initialize () { + thisObject.container.frame.width = UI_PANEL.WIDTH.LARGE + thisObject.container.frame.height = viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y // UI_PANEL.HEIGHT.LARGE; - thisObject.container.frame.width = UI_PANEL.WIDTH.LARGE; - thisObject.container.frame.height = viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y; //UI_PANEL.HEIGHT.LARGE; + var position = { + x: viewPort.visibleArea.topLeft.x, + y: viewPort.visibleArea.bottomLeft.y - thisObject.container.frame.height + } - var position = { - x: viewPort.visibleArea.topLeft.x, - y: viewPort.visibleArea.bottomLeft.y - thisObject.container.frame.height - }; - - thisObject.container.frame.position = position; + thisObject.container.frame.position = position /* First thing is to build the productCards array */ - let devTeams = ecosystem.getTeams(); + let devTeams = ecosystem.getTeams() - for (let i = 0; i < devTeams.length; i++) { + for (let i = 0; i < devTeams.length; i++) { + let devTeam = devTeams[i] - let devTeam = devTeams[i]; + for (let j = 0; j < devTeam.bots.length; j++) { + let bot = devTeam.bots[j] - for (let j = 0; j < devTeam.bots.length; j++) { - - let bot = devTeam.bots[j]; - - if (bot.products !== undefined) { - - for (let k = 0; k < bot.products.length; k++) { - - let product = bot.products[k]; + if (bot.products !== undefined) { + for (let k = 0; k < bot.products.length; k++) { + let product = bot.products[k] /* Now we create Product objects */ - let productCard = newProductCard(); + let productCard = newProductCard() - productCard.devTeam = devTeam; - productCard.bot = bot; - productCard.product = product; + productCard.devTeam = devTeam + productCard.bot = bot + productCard.product = product - productCard.code = devTeam.codeName + '-' + bot.codeName + '-' + product.codeName; + productCard.code = devTeam.codeName + '-' + bot.codeName + '-' + product.codeName /* Initialize it */ - productCard.initialize(); + productCard.initialize() /* Container Stuff */ - productCard.container.displacement.parentDisplacement = thisObject.container.displacement; - productCard.container.frame.parentFrame = thisObject.container.frame; - productCard.container.parentContainer = thisObject.container; - productCard.container.isWheelable = true; + productCard.container.displacement.parentDisplacement = thisObject.container.displacement + productCard.container.frame.parentFrame = thisObject.container.frame + productCard.container.parentContainer = thisObject.container + productCard.container.isWheelable = true /* Positioning within thisObject Panel */ - let position = { - x: 10, - y: thisObject.container.frame.height - thisObject.container.frame.getBodyHeight() - }; + let position = { + x: 10, + y: thisObject.container.frame.height - thisObject.container.frame.getBodyHeight() + } - productCard.container.frame.position.x = position.x; - productCard.container.frame.position.y = position.y + lastY; + productCard.container.frame.position.x = position.x + productCard.container.frame.position.y = position.y + lastY - lastY = lastY + productCard.container.frame.height; + lastY = lastY + productCard.container.frame.height /* Add to the Product Array */ - productCards.push(productCard); + productCards.push(productCard) /* Add to Visible Product Array */ - if (productCard.container.frame.position.y + productCard.container.frame.height < thisObject.container.frame.height) { - - visibleProductCards.push(productCard); - - } + if (productCard.container.frame.position.y + productCard.container.frame.height < thisObject.container.frame.height) { + visibleProductCards.push(productCard) + } /* Listen to Status Changes Events */ - productCard.container.eventHandler.listenToEvent('Status Changed', onProductCardStatusChanged); - productCard.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel); + productCard.container.eventHandler.listenToEvent('Status Changed', onProductCardStatusChanged) + productCard.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel) + } + } + } + } - } - } - } - } + thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel) + isInitialized = true + } - thisObject.container.eventHandler.listenToEvent("Mouse Wheel", onMouseWheel); - isInitialized = true; + function onMouseWheel (pDelta) { + if (pDelta > 0) { + pDelta = -1 + } else { + pDelta = 1 + } - } + firstVisibleCard = firstVisibleCard + pDelta - function onMouseWheel(pDelta) { + let availableSlots = visibleProductCards.length - if (pDelta > 0) { - pDelta = -1; - } else { - pDelta = 1; - } + if (firstVisibleCard < 1) { firstVisibleCard = 1 } + if (firstVisibleCard > (productCards.length - availableSlots + 1)) { firstVisibleCard = productCards.length - availableSlots + 1 } - firstVisibleCard = firstVisibleCard + pDelta; + visibleProductCards = [] + var lastY = 5 - let availableSlots = visibleProductCards.length; - - if (firstVisibleCard < 1) { firstVisibleCard = 1; } - if (firstVisibleCard > (productCards.length - availableSlots + 1)) { firstVisibleCard = productCards.length - availableSlots + 1; } - - visibleProductCards = []; - var lastY = 5; - - for (let i = 0; i < productCards.length; i++) { - - if (i + 1 >= firstVisibleCard && i + 1 < firstVisibleCard + availableSlots) { - - let productCard = productCards[i]; + for (let i = 0; i < productCards.length; i++) { + if (i + 1 >= firstVisibleCard && i + 1 < firstVisibleCard + availableSlots) { + let productCard = productCards[i] /* Positioning within thisObject Panel */ - let position = { - x: 10, - y: thisObject.container.frame.height - thisObject.container.frame.getBodyHeight() - }; - productCard.container.frame.position.x = position.x; - productCard.container.frame.position.y = position.y + lastY; + let position = { + x: 10, + y: thisObject.container.frame.height - thisObject.container.frame.getBodyHeight() + } + productCard.container.frame.position.x = position.x + productCard.container.frame.position.y = position.y + lastY - lastY = lastY + productCard.container.frame.height; + lastY = lastY + productCard.container.frame.height /* Add to Visible Product Array */ - visibleProductCards.push(productCard); - } - } - } + visibleProductCards.push(productCard) + } + } + } - function onProductCardStatusChanged(pProductCard) { - - thisObject.container.eventHandler.raiseEvent('Product Card Status Changed', pProductCard); - - } - - function getLoadingProductCards() { + function onProductCardStatusChanged (pProductCard) { + thisObject.container.eventHandler.raiseEvent('Product Card Status Changed', pProductCard) + } + function getLoadingProductCards () { /* Returns all productCards which status is LOADING */ - let onProducts = []; + let onProducts = [] - for (let i = 0; i < productCards.length; i++) { + for (let i = 0; i < productCards.length; i++) { + if (productCards[i].status === PRODUCT_CARD_STATUS.LOADING) { + onProducts.push(productCards[i]) + } + } - if (productCards[i].status === PRODUCT_CARD_STATUS.LOADING) { + return onProducts + } - onProducts.push(productCards[i]); - } - } - - return onProducts; - } - - function getContainer(point) { - - var container; + function getContainer (point) { + var container /* First we check if thisObject point is inside thisObject space. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { /* Now we see which is the inner most container that has it */ + for (var i = 0; i < visibleProductCards.length; i++) { + container = visibleProductCards[i].getContainer(point) - for (var i = 0; i < visibleProductCards.length; i++) { - - container = visibleProductCards[i].getContainer(point); - - if (container !== undefined) { - + if (container !== undefined) { /* We found an inner container which has the point. We return it. */ - return container; - } - } + return container + } + } /* The point does not belong to any inner container, so we return the current container. */ - return thisObject.container; - - } else { - + return thisObject.container + } else { /* This point does not belong to thisObject space. */ - return undefined; - } + return undefined + } + } - } + function draw () { + if (isInitialized === false) { return } + thisObject.container.frame.draw(false, false, true) - function draw() { - - if (isInitialized === false) {return;} - - thisObject.container.frame.draw(false, false, true); - - for (let i = 0; i < visibleProductCards.length; i++) { - visibleProductCards[i].draw(); - } - - } - -} \ No newline at end of file + for (let i = 0; i < visibleProductCards.length; i++) { + visibleProductCards[i].draw() + } + } + } diff --git a/Panels/TimeControlPanel.js b/Panels/TimeControlPanel.js index a5191f5f7..0a7e859de 100644 --- a/Panels/TimeControlPanel.js +++ b/Panels/TimeControlPanel.js @@ -1,177 +1,159 @@ - -function newTimeControlPanel() { +  +function newTimeControlPanel () { + let thisObject = { + container: undefined, + setDatetime: setDatetime, + datetimeDisplay: undefined, + stepDisplay: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - let thisObject = { - container: undefined, - setDatetime: setDatetime, - datetimeDisplay: undefined, - stepDisplay: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + let container = newContainer() + container.initialize() + container.isDraggeable = true + thisObject.container = container + thisObject.container.frame.containerName = 'Current Datetime' - let container = newContainer(); - container.initialize(); - container.isDraggeable = true; - thisObject.container = container; - thisObject.container.frame.containerName = "Current Datetime"; + let timePeriod - let timePeriod; + return thisObject - return thisObject; + function initialize () { + thisObject.container.frame.width = UI_PANEL.WIDTH.SMALL + thisObject.container.frame.height = UI_PANEL.HEIGHT.SMALL - function initialize() { + let position = { + x: (viewPort.visibleArea.topRight.x - viewPort.visibleArea.topLeft.x) / 2 - thisObject.container.frame.width / 2, + y: viewPort.visibleArea.bottomLeft.y - thisObject.container.frame.height + } - thisObject.container.frame.width = UI_PANEL.WIDTH.SMALL; - thisObject.container.frame.height = UI_PANEL.HEIGHT.SMALL; + thisObject.container.frame.position = position - let position = { - x: (viewPort.visibleArea.topRight.x - viewPort.visibleArea.topLeft.x) / 2 - thisObject.container.frame.width / 2, - y: viewPort.visibleArea.bottomLeft.y - thisObject.container.frame.height - }; + let buttonPosition - thisObject.container.frame.position = position; + let buttonNames = ['Fast Backwards', 'Play Backwards', 'Step Backwards', 'Pause', 'Step Forward', 'Play Forward', 'Fast Forward'] + let lastX = 0 - let buttonPosition; + let datetime = INITIAL_DATE - let buttonNames = ['Fast Backwards', 'Play Backwards', 'Step Backwards', 'Pause', 'Step Forward', 'Play Forward', 'Fast Forward']; - let lastX = 0; + let datetimeDisplay = { + currentDatetime: datetime, + addTime: addTime, + draw: drawTimeDisplay + } - let datetime = INITIAL_DATE; - - let datetimeDisplay = { - currentDatetime: datetime, - addTime: addTime, - draw: drawTimeDisplay - }; - - thisObject.datetimeDisplay = datetimeDisplay; + thisObject.datetimeDisplay = datetimeDisplay /* Here we will listen to the event when time was changed due to a Bot Execution. */ - canvas.bottomSpace.playStopButton.container.eventHandler.listenToEvent("Bot Execution Changed Datetime", onBotChangedTime); - canvas.bottomSpace.playStopButton.setDatetime(datetime); + canvas.bottomSpace.playStopButton.container.eventHandler.listenToEvent('Bot Execution Changed Datetime', onBotChangedTime) + canvas.bottomSpace.playStopButton.setDatetime(datetime) - viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged); - timePeriod = INITIAL_TIME_PERIOD; - } + viewPort.eventHandler.listenToEvent('Zoom Changed', onZoomChanged) + timePeriod = INITIAL_TIME_PERIOD + } - function onBotChangedTime(pNewDatetime) { + function onBotChangedTime (pNewDatetime) { + let newDatetime = new Date(pNewDatetime) - let newDatetime = new Date(pNewDatetime); + thisObject.container.eventHandler.raiseEvent('Datetime Changed', newDatetime) + } - thisObject.container.eventHandler.raiseEvent("Datetime Changed", newDatetime); + function onZoomChanged (event) { + timePeriod = recalculatePeriod(event.newLevel) + } - } - - function onZoomChanged(event) { - - timePeriod = recalculatePeriod(event.newLevel); - - } - - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* First we check if thisObject point is inside thisObject space. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { /* The point does not belong to any inner container, so we return the current container. */ - return thisObject.container; - - } else { - + return thisObject.container + } else { /* This point does not belong to thisObject space. */ - return undefined; - } - + return undefined } + } - function setDatetime(pDatetime) { + function setDatetime (pDatetime) { + thisObject.datetimeDisplay.currentDatetime = new Date(pDatetime) + canvas.bottomSpace.playStopButton.setDatetime(pDatetime) + } - thisObject.datetimeDisplay.currentDatetime = new Date(pDatetime); - canvas.bottomSpace.playStopButton.setDatetime(pDatetime); - } + function addTime (seconds) { + let newDate = thisObject.datetimeDisplay.currentDatetime - function addTime(seconds) { + newDate.setSeconds(newDate.getSeconds() + seconds) + thisObject.datetimeDisplay.currentDatetime = newDate + } - let newDate = thisObject.datetimeDisplay.currentDatetime; + function draw () { + thisObject.container.frame.draw(false, false, true) - newDate.setSeconds(newDate.getSeconds() + seconds); - thisObject.datetimeDisplay.currentDatetime = newDate; + thisObject.datetimeDisplay.draw() + } - } + function drawTimeDisplay () { + let fontSize = 10 - function draw() { + let label = thisObject.datetimeDisplay.currentDatetime.toUTCString() + let labelArray = label.split(' ') - thisObject.container.frame.draw(false, false, true); - - thisObject.datetimeDisplay.draw(); - - } - - function drawTimeDisplay() { - - let fontSize = 10; - - let label = thisObject.datetimeDisplay.currentDatetime.toUTCString(); - let labelArray = label.split(" "); - - label = labelArray[0] + " " + labelArray[1] + " " + labelArray[2] + " " + labelArray[3]; + label = labelArray[0] + ' ' + labelArray[1] + ' ' + labelArray[2] + ' ' + labelArray[3] /* Now we transform x on the actual coordinate on the canvas. */ - let labelPoint = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: thisObject.container.frame.height * 4.4 / 10 - }; + let labelPoint = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: thisObject.container.frame.height * 4.4 / 10 + } - labelPoint = thisObject.container.frame.frameThisPoint(labelPoint); + labelPoint = thisObject.container.frame.frameThisPoint(labelPoint) - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) /* The time */ - label = labelArray[4] + " " + labelArray[5]; + label = labelArray[4] + ' ' + labelArray[5] /* Now we transform x on the actual coordinate on the canvas. */ - labelPoint = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: thisObject.container.frame.height * 6.5 / 10 - }; - - labelPoint = thisObject.container.frame.frameThisPoint(labelPoint); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); - - if (timePeriod > _45_MINUTES_IN_MILISECONDS) { - label = timePeriod / _1_HOUR_IN_MILISECONDS + ' hs'; - } else { - label = timePeriod / _1_MINUTE_IN_MILISECONDS + ' min'; - } - - /* Now we transform x on the actual coordinate on the canvas. */ - - labelPoint = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: thisObject.container.frame.height * 8.5 / 10 - }; - - labelPoint = thisObject.container.frame.frameThisPoint(labelPoint); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); - + labelPoint = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: thisObject.container.frame.height * 6.5 / 10 } -} \ No newline at end of file + + labelPoint = thisObject.container.frame.frameThisPoint(labelPoint) + + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + + if (timePeriod > _45_MINUTES_IN_MILISECONDS) { + label = timePeriod / _1_HOUR_IN_MILISECONDS + ' hs' + } else { + label = timePeriod / _1_MINUTE_IN_MILISECONDS + ' min' + } + + /* Now we transform x on the actual coordinate on the canvas. */ + + labelPoint = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: thisObject.container.frame.height * 8.5 / 10 + } + + labelPoint = thisObject.container.frame.frameThisPoint(labelPoint) + + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + } +} diff --git a/PlottersManager.js b/PlottersManager.js index a42277cc8..f4448ea02 100644 --- a/PlottersManager.js +++ b/PlottersManager.js @@ -1,806 +1,689 @@ -function newPlottersManager() { +function newPlottersManager () { + const MODULE_NAME = 'Plotters Manager' + const INFO_LOG = false + const INTENSIVE_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Plotters Manager"; - const INFO_LOG = false; - const INTENSIVE_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let productPlotters = [] + let competitionPlotters = [] - let productPlotters = []; - let competitionPlotters = []; + let timePeriod = INITIAL_TIME_PERIOD + let datetime = INITIAL_DATE - let timePeriod = INITIAL_TIME_PERIOD; - let datetime = INITIAL_DATE; + let thisObject = { + setDatetime: setDatetime, + setTimePeriod: setTimePeriod, + positionAtDatetime: positionAtDatetime, + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - setDatetime: setDatetime, - setTimePeriod: setTimePeriod, - positionAtDatetime: positionAtDatetime, - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + container.displacement.containerName = 'Plotter Manager' + container.frame.containerName = 'Plotter Manager' - container.displacement.containerName = "Plotter Manager"; - container.frame.containerName = "Plotter Manager"; + let initializationReady = false - let initializationReady = false; + let productsPanel - let productsPanel; + return thisObject - return thisObject; - - function initialize(pProductsPanel, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function initialize (pProductsPanel, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } /* Remember the Products Panel */ - productsPanel = pProductsPanel; + productsPanel = pProductsPanel /* Listen to the event of change of status */ - productsPanel.container.eventHandler.listenToEvent("Product Card Status Changed", onProductCardStatusChanged); + productsPanel.container.eventHandler.listenToEvent('Product Card Status Changed', onProductCardStatusChanged) - initializeCompetitionPlotters(onCompetitionPlottersInitialized); + initializeCompetitionPlotters(onCompetitionPlottersInitialized) - canvas.bottomSpace.chartAspectRatio.container.eventHandler.listenToEvent("Chart Aspect Ratio Changed", onAspectRatioChanged); + canvas.bottomSpace.chartAspectRatio.container.eventHandler.listenToEvent('Chart Aspect Ratio Changed', onAspectRatioChanged) - function onAspectRatioChanged(pAspectRatio) { - - thisObject.container.frame.height = CHART_SPACE_HEIGHT * pAspectRatio.y; + function onAspectRatioChanged (pAspectRatio) { + thisObject.container.frame.height = CHART_SPACE_HEIGHT * pAspectRatio.y /* First the Product Plotters. */ - for (let i = 0; i < productPlotters.length; i++) { + for (let i = 0; i < productPlotters.length; i++) { + let productPlotter = productPlotters[i] + productPlotter.plotter.container.frame.width = thisObject.container.frame.width + productPlotter.plotter.container.frame.height = thisObject.container.frame.height - let productPlotter = productPlotters[i]; - productPlotter.plotter.container.frame.width = thisObject.container.frame.width; - productPlotter.plotter.container.frame.height = thisObject.container.frame.height; - - if (productPlotter.plotter.recalculateScale !== undefined) { - - productPlotter.plotter.recalculateScale(); - - } - } + if (productPlotter.plotter.recalculateScale !== undefined) { + productPlotter.plotter.recalculateScale() + } + } /* Then the competition plotters. */ - for (let i = 0; i < competitionPlotters.length; i++) { + for (let i = 0; i < competitionPlotters.length; i++) { + let competitionPlotter = competitionPlotters[i] + competitionPlotter.plotter.container.frame.width = thisObject.container.frame.width + competitionPlotter.plotter.container.frame.height = thisObject.container.frame.height - let competitionPlotter = competitionPlotters[i]; - competitionPlotter.plotter.container.frame.width = thisObject.container.frame.width; - competitionPlotter.plotter.container.frame.height = thisObject.container.frame.height; - - if (competitionPlotter.plotter.recalculateScale !== undefined) { - - competitionPlotter.plotter.recalculateScale(); - - } - } - } - - function onCompetitionPlottersInitialized(err) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileCursorReady -> Received Unexpected Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - } - - initializeProductPlotters(onProductPlottersInitialized); - - function onProductPlottersInitialized(err) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Received OK Response."); } - - initializationReady = true; - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Received Unexpected Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onCompetitionPlottersInitialized -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (competitionPlotter.plotter.recalculateScale !== undefined) { + competitionPlotter.plotter.recalculateScale() + } } - } - - function initializeCompetitionPlotters(callBack) { + } + function onCompetitionPlottersInitialized (err) { try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> Entering function."); } + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> Received OK Response.') } + break + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileCursorReady -> Received Unexpected Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + } + + initializeProductPlotters(onProductPlottersInitialized) + + function onProductPlottersInitialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Entering function.') } + + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Received OK Response.') } + + initializationReady = true + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + break + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> Received Unexpected Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onCompetitionPlottersInitialized -> onProductPlottersInitialized -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onCompetitionPlottersInitialized -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + + function initializeCompetitionPlotters (callBack) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> Entering function.') } /* At this current version of the platform, we will support only one competition with only one plotter. */ - const COMPETITION_HOST = "AAArena"; - const COMPETITION = "Weekend-Deathmatch"; + const COMPETITION_HOST = 'AAArena' + const COMPETITION = 'Weekend-Deathmatch' - let objName = COMPETITION_HOST + "-" + COMPETITION; - let storage = newCompetitionStorage(objName); + let objName = COMPETITION_HOST + '-' + COMPETITION + let storage = newCompetitionStorage(objName) - let host = ecosystem.getHost(COMPETITION_HOST); - let competition = ecosystem.getCompetition(host, COMPETITION); + let host = ecosystem.getHost(COMPETITION_HOST) + let competition = ecosystem.getCompetition(host, COMPETITION) - storage.initialize(host, competition, DEFAULT_EXCHANGE, DEFAULT_MARKET, onCompetitionStorageInitialized); + storage.initialize(host, competition, DEFAULT_EXCHANGE, DEFAULT_MARKET, onCompetitionStorageInitialized) - function onCompetitionStorageInitialized(err) { + function onCompetitionStorageInitialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Entering function.') } - try { + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Received OK Response.') } + break + } - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Entering function."); } + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Received FAIL Response.') } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Received FAIL Response."); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Received Unexpected Response."); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - } + default: { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> Received Unexpected Response.') } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + } /* Now we have all the initial data loaded and ready to be delivered to the new instance of the plotter. */ - let plotter = getNewPlotter(competition.plotter.host, competition.plotter.codeName, competition.plotter.moduleName); + let plotter = getNewPlotter(competition.plotter.host, competition.plotter.codeName, competition.plotter.moduleName) - plotter.container.displacement.parentDisplacement = thisObject.container.displacement; - plotter.container.frame.parentFrame = thisObject.container.frame; + plotter.container.displacement.parentDisplacement = thisObject.container.displacement + plotter.container.frame.parentFrame = thisObject.container.frame - plotter.container.parentContainer = thisObject.container; + plotter.container.parentContainer = thisObject.container - plotter.container.frame.width = thisObject.container.frame.width * 1; - plotter.container.frame.height = thisObject.container.frame.height * 1; + plotter.container.frame.width = thisObject.container.frame.width * 1 + plotter.container.frame.height = thisObject.container.frame.height * 1 - plotter.container.frame.position.x = thisObject.container.frame.width / 2 - plotter.container.frame.width / 2; - plotter.container.frame.position.y = thisObject.container.frame.height / 2 - plotter.container.frame.height / 2; + plotter.container.frame.position.x = thisObject.container.frame.width / 2 - plotter.container.frame.width / 2 + plotter.container.frame.position.y = thisObject.container.frame.height / 2 - plotter.container.frame.height / 2 /* We add the profile picture of each participant, because the plotter will need it. */ - for (let k = 0; k < competition.participants.length; k++) { + for (let k = 0; k < competition.participants.length; k++) { + let participant = competition.participants[k] + let devTeam = ecosystem.getTeam(participant.devTeam) + let bot = ecosystem.getBot(devTeam, participant.bot) + participant.profilePicture = bot.profilePicture + } - let participant = competition.participants[k]; - let devTeam = ecosystem.getTeam(participant.devTeam); - let bot = ecosystem.getBot(devTeam, participant.bot); - participant.profilePicture = bot.profilePicture; + plotter.initialize(competition, storage, datetime, timePeriod, onPlotterInizialized) - } + function onPlotterInizialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Entering function.') } - plotter.initialize(competition, storage, datetime, timePeriod, onPlotterInizialized); + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Received OK Response.') } + break + } - function onPlotterInizialized(err) { + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Received FAIL Response.') } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - try { + default: { + if (INFO_LOG === true) { logger.write('[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Received Unexpected Response.') } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + } - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Entering function."); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Received FAIL Response."); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> Received Unexpected Response."); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - } - - let competitionPlotter = { - plotter: plotter, - storage: storage - }; + let competitionPlotter = { + plotter: plotter, + storage: storage + } /* Add the new Active Protter to the Array */ - competitionPlotters.push(competitionPlotter); + competitionPlotters.push(competitionPlotter) /* Create The Profie Picture FloatingObject */ - if (competitionPlotter.plotter.payload !== undefined) { + if (competitionPlotter.plotter.payload !== undefined) { + for (let k = 0; k < competition.participants.length; k++) { + let participant = competition.participants[k] + let devTeam = ecosystem.getTeam(participant.devTeam) + let bot = ecosystem.getBot(devTeam, participant.bot) + let imageId = participant.devTeam + '.' + participant.profilePicture - for (let k = 0; k < competition.participants.length; k++) { + const TEAM = devTeam.codeName.toLowerCase() + const BOT = bot.codeName.toLowerCase() - let participant = competition.participants[k]; - let devTeam = ecosystem.getTeam(participant.devTeam); - let bot = ecosystem.getBot(devTeam, participant.bot); - let imageId = participant.devTeam + "." + participant.profilePicture; + let botAvatar = new Image() - const TEAM = devTeam.codeName.toLowerCase(); - const BOT = bot.codeName.toLowerCase(); + botAvatar.src = window.canvasApp.context.fbProfileImages.get(TEAM + '-' + BOT) - let botAvatar = new Image(); - - botAvatar.src = window.canvasApp.context.fbProfileImages.get(TEAM + "-" + BOT); + competitionPlotter.plotter.payload[k].profile.downLabel = bot.displayName + competitionPlotter.plotter.payload[k].profile.imageId = imageId + competitionPlotter.plotter.payload[k].profile.botAvatar = botAvatar - competitionPlotter.plotter.payload[k].profile.downLabel = bot.displayName; - competitionPlotter.plotter.payload[k].profile.imageId = imageId; - competitionPlotter.plotter.payload[k].profile.botAvatar = botAvatar; + canvas.floatingSpace.profileBalls.createNewProfileBall(competitionPlotter.plotter.payload[k], onProfileBallCreated) - canvas.floatingSpace.profileBalls.createNewProfileBall(competitionPlotter.plotter.payload[k], onProfileBallCreated) - - function onProfileBallCreated(err, pProfileHandle) { - - competitionPlotter.plotter.payload[k].profile.handle = pProfileHandle; - - } - } - } - - callBack(GLOBAL.DEFAULT_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); + function onProfileBallCreated (err, pProfileHandle) { + competitionPlotter.plotter.payload[k].profile.handle = pProfileHandle + } } + } + + callBack(GLOBAL.DEFAULT_OK_RESPONSE) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> onPlotterInizialized -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } - + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeCompetitionPlotters -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initializeCompetitionPlotters -> onCompetitionStorageInitialized -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initializeCompetitionPlotters -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function initializeProductPlotters(callBack) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> Entering function."); } + function initializeProductPlotters (callBack) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> Entering function.') } /* Lets get all the cards that needs to be loaded. */ - let initializationCounter = 0; - let loadingProductCards = productsPanel.getLoadingProductCards(); - let okCounter = 0; - let failCounter = 0; - - for (let i = 0; i < loadingProductCards.length; i++) { + let initializationCounter = 0 + let loadingProductCards = productsPanel.getLoadingProductCards() + let okCounter = 0 + let failCounter = 0 + for (let i = 0; i < loadingProductCards.length; i++) { /* For each one, we will initialize the associated plotter. */ - initializeProductPlotter(loadingProductCards[i], onProductPlotterInitialized); + initializeProductPlotter(loadingProductCards[i], onProductPlotterInitialized) - function onProductPlotterInitialized(err) { + function onProductPlotterInitialized (err) { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> Entering function."); } + initializationCounter++ - initializationCounter++; + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Received OK Response.') } + okCounter++ + break + } - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Received FAIL Response.') } + failCounter++ + break + } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Received OK Response."); } - okCounter++; - break; - } + default: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Received Unexpected Response.') } + failCounter++ + break + } + } - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> initializationCounter = ' + initializationCounter) } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> okCounter = ' + okCounter) } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> failCounter = ' + failCounter) } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> loadingProductCards.length = ' + loadingProductCards.length) } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Received FAIL Response."); } - failCounter++; - break; - } + if (initializationCounter === loadingProductCards.length) { + // This was the last one. - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Received Unexpected Response."); } - failCounter++; - break; - } - } - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> initializationCounter = " + initializationCounter); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> okCounter = " + okCounter); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> failCounter = " + failCounter); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> loadingProductCards.length = " + loadingProductCards.length); } - - if (initializationCounter === loadingProductCards.length) { // This was the last one. - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Last Product Loaded."); } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> onProductPlotterInitialized -> Last Product Loaded.') } /* If less than 50% of plotters are initialized then we return FAIL. */ - if (okCounter >= 1) { - callBack(GLOBAL.DEFAULT_OK_RESPONSE); - } else { - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - } + if (okCounter >= 1) { + callBack(GLOBAL.DEFAULT_OK_RESPONSE) + } else { + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeProductPlotters -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); + } } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initializeProductPlotters -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function initializeProductPlotter(pProductCard, callBack) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> Entering function."); } + function initializeProductPlotter (pProductCard, callBack) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> Entering function.') } /* Before Initializing a Plotter, we need the Storage it will use, loaded with the files it will initially need. */ - let objName = pProductCard.devTeam.codeName + "-" + pProductCard.bot.codeName + "-" + pProductCard.product.codeName; - let storage = newProductStorage(objName); + let objName = pProductCard.devTeam.codeName + '-' + pProductCard.bot.codeName + '-' + pProductCard.product.codeName + let storage = newProductStorage(objName) - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> objName = " + objName); } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> objName = ' + objName) } /* - + Before Initializing the Storage, we will put the Product Card to listen to the events the storage will raise every time a file is loaded, - so that the UI can somehow show this. There are different types of events. - + so that the UI can somehow show this. There are different types of events. + */ - for (let i = 0; i < pProductCard.product.dataSets.length; i++) { + for (let i = 0; i < pProductCard.product.dataSets.length; i++) { + let thisSet = pProductCard.product.dataSets[i] - let thisSet = pProductCard.product.dataSets[i]; + switch (thisSet.type) { + case 'Market Files': { + storage.eventHandler.listenToEvent('Market File Loaded', pProductCard.onMarketFileLoaded) + } + break - switch (thisSet.type) { - case 'Market Files': { - storage.eventHandler.listenToEvent('Market File Loaded', pProductCard.onMarketFileLoaded); - } - break; + case 'Daily Files': { + storage.eventHandler.listenToEvent('Daily File Loaded', pProductCard.onDailyFileLoaded) + } + break - case 'Daily Files': { - storage.eventHandler.listenToEvent('Daily File Loaded', pProductCard.onDailyFileLoaded); - } - break; + case 'Single File': { + storage.eventHandler.listenToEvent('Single File Loaded', pProductCard.onSingleFileLoaded) + } + break - case 'Single File': { - storage.eventHandler.listenToEvent('Single File Loaded', pProductCard.onSingleFileLoaded); - } - break; + case 'File Sequence': { + storage.eventHandler.listenToEvent('File Sequence Loaded', pProductCard.onFileSequenceLoaded) + } + break + } + } - case 'File Sequence': { - storage.eventHandler.listenToEvent('File Sequence Loaded', pProductCard.onFileSequenceLoaded); - } - break; - } + storage.initialize(pProductCard.devTeam, pProductCard.bot, pProductCard.product, DEFAULT_EXCHANGE, DEFAULT_MARKET, datetime, timePeriod, onProductStorageInitialized) + + function onProductStorageInitialized (err) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> key = ' + pProductCard.devTeam.codeName + '-' + pProductCard.bot.codeName + '-' + pProductCard.product.codeName) } + + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> Received OK Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> The plotter will be started.') } + break } - storage.initialize(pProductCard.devTeam, pProductCard.bot, pProductCard.product, DEFAULT_EXCHANGE, DEFAULT_MARKET, datetime, timePeriod, onProductStorageInitialized); + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> Received FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> The plotter will not be started.') } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - function onProductStorageInitialized(err) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> key = " + pProductCard.devTeam.codeName + "-" + pProductCard.bot.codeName + "-" + pProductCard.product.codeName); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> Received OK Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> The plotter will be started."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> Received FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> The plotter will not be started."); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> Received Unexpected Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> The plotter will not be started."); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - } + default: { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> Received Unexpected Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> The plotter will not be started.') } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + } /* Now we have all the initial data loaded and ready to be delivered to the new instance of the plotter. */ - let plotter = getNewPlotter(pProductCard.product.plotter.devTeam, pProductCard.product.plotter.codeName, pProductCard.product.plotter.moduleName); + let plotter = getNewPlotter(pProductCard.product.plotter.devTeam, pProductCard.product.plotter.codeName, pProductCard.product.plotter.moduleName) - plotter.container.displacement.parentDisplacement = thisObject.container.displacement; - plotter.container.frame.parentFrame = thisObject.container.frame; + plotter.container.displacement.parentDisplacement = thisObject.container.displacement + plotter.container.frame.parentFrame = thisObject.container.frame - plotter.container.parentContainer = thisObject.container; + plotter.container.parentContainer = thisObject.container - plotter.container.frame.width = thisObject.container.frame.width * 1; - plotter.container.frame.height = thisObject.container.frame.height * 1; + plotter.container.frame.width = thisObject.container.frame.width * 1 + plotter.container.frame.height = thisObject.container.frame.height * 1 - plotter.container.frame.position.x = thisObject.container.frame.width / 2 - plotter.container.frame.width / 2; - plotter.container.frame.position.y = thisObject.container.frame.height / 2 - plotter.container.frame.height / 2; + plotter.container.frame.position.x = thisObject.container.frame.width / 2 - plotter.container.frame.width / 2 + plotter.container.frame.position.y = thisObject.container.frame.height / 2 - plotter.container.frame.height / 2 - plotter.initialize(storage, DEFAULT_EXCHANGE, DEFAULT_MARKET, datetime, timePeriod, onPlotterInizialized); + plotter.initialize(storage, DEFAULT_EXCHANGE, DEFAULT_MARKET, datetime, timePeriod, onPlotterInizialized) - function onPlotterInizialized() { + function onPlotterInizialized () { + try { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> key = ' + pProductCard.product.plotter.devTeam + '-' + pProductCard.product.plotter.codeName + '-' + pProductCard.product.plotter.moduleName) } - try { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> key = " + pProductCard.product.plotter.devTeam + "-" + pProductCard.product.plotter.codeName + "-" + pProductCard.product.plotter.moduleName); } - - try { - //plotter.positionAtDatetime(INITIAL_DATE); - } catch (err) { + try { + // plotter.positionAtDatetime(INITIAL_DATE); + } catch (err) { // If the plotter does not implement this function its ok. - } + } - let productPlotter = { - productCard: pProductCard, - plotter: plotter, - storage: storage, - profile: undefined, - notes: undefined - }; + let productPlotter = { + productCard: pProductCard, + plotter: plotter, + storage: storage, + profile: undefined, + notes: undefined + } /* Let the Plotter listen to the event of Cursor Files loaded, so that it can reack recalculating if needed. */ - storage.eventHandler.listenToEvent('Daily File Loaded', plotter.onDailyFileLoaded); + storage.eventHandler.listenToEvent('Daily File Loaded', plotter.onDailyFileLoaded) /* Lets load now this plotter panels. */ - productPlotter.panels = []; + productPlotter.panels = [] - for (let i = 0; i < pProductCard.product.plotter.module.panels.length; i++) { + for (let i = 0; i < pProductCard.product.plotter.module.panels.length; i++) { + let panelConfig = pProductCard.product.plotter.module.panels[i] - let panelConfig = pProductCard.product.plotter.module.panels[i]; + let parameters = { + devTeam: pProductCard.product.plotter.devTeam, + plotterCodeName: pProductCard.product.plotter.codeName, + moduleCodeName: pProductCard.product.plotter.moduleName, + panelCodeName: panelConfig.codeName + } - let parameters = { - devTeam: pProductCard.product.plotter.devTeam, - plotterCodeName: pProductCard.product.plotter.codeName, - moduleCodeName: pProductCard.product.plotter.moduleName, - panelCodeName: panelConfig.codeName - } - - let plotterPanelHandle = canvas.panelsSpace.createNewPanel("Plotter Panel", parameters); - let plotterPanel = canvas.panelsSpace.getPanel(plotterPanelHandle); + let plotterPanelHandle = canvas.panelsSpace.createNewPanel('Plotter Panel', parameters) + let plotterPanel = canvas.panelsSpace.getPanel(plotterPanelHandle) /* Connect Panel to the Plotter via an Event. */ - if (panelConfig.event !== undefined) { + if (panelConfig.event !== undefined) { + productPlotter.plotter.container.eventHandler.listenToEvent(panelConfig.event, plotterPanel.onEventRaised) + } - productPlotter.plotter.container.eventHandler.listenToEvent(panelConfig.event, plotterPanel.onEventRaised); - - } - - productPlotter.panels.push(plotterPanelHandle); - } + productPlotter.panels.push(plotterPanelHandle) + } /* Create The Profie Picture FloatingObject */ - if (productPlotter.plotter.payload !== undefined) { + if (productPlotter.plotter.payload !== undefined) { + let imageId = pProductCard.bot.devTeam + '.' + pProductCard.bot.profilePicture - let imageId = pProductCard.bot.devTeam + "." + pProductCard.bot.profilePicture; + productPlotter.plotter.payload.profile.upLabel = pProductCard.product.shortDisplayName + productPlotter.plotter.payload.profile.downLabel = pProductCard.bot.displayName + productPlotter.plotter.payload.profile.imageId = imageId + productPlotter.plotter.payload.profile.botAvatar = pProductCard.bot.avatar - productPlotter.plotter.payload.profile.upLabel = pProductCard.product.shortDisplayName; - productPlotter.plotter.payload.profile.downLabel = pProductCard.bot.displayName; - productPlotter.plotter.payload.profile.imageId = imageId; - productPlotter.plotter.payload.profile.botAvatar = pProductCard.bot.avatar; + canvas.floatingSpace.profileBalls.createNewProfileBall(productPlotter.plotter.payload, onProfileBallCreated) - canvas.floatingSpace.profileBalls.createNewProfileBall(productPlotter.plotter.payload, onProfileBallCreated) - - function onProfileBallCreated(err, pProfileHandle) { - - productPlotter.profile = pProfileHandle; + function onProfileBallCreated (err, pProfileHandle) { + productPlotter.profile = pProfileHandle /* There is no policy yet of what to do if this fails. */ - } + } /* Create the Text Notes */ - canvas.floatingSpace.noteSets.createNoteSet(productPlotter.plotter.payload, productPlotter.plotter.container.eventHandler, onNoteSetCreated); + canvas.floatingSpace.noteSets.createNoteSet(productPlotter.plotter.payload, productPlotter.plotter.container.eventHandler, onNoteSetCreated) - function onNoteSetCreated(err, pNoteSetHandle) { - - productPlotter.noteSet = pNoteSetHandle; + function onNoteSetCreated (err, pNoteSetHandle) { + productPlotter.noteSet = pNoteSetHandle /* There is no policy yet of what to do if this fails. */ - } - } + } + } /* Add the new Active Protter to the Array */ - productPlotters.push(productPlotter); + productPlotters.push(productPlotter) - callBack(GLOBAL.DEFAULT_OK_RESPONSE); - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeProductPlotter -> onProductStorageInitialized -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); - } + callBack(GLOBAL.DEFAULT_OK_RESPONSE) + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } - + } } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initializeProductPlotter -> err = " + err); } - callBack(GLOBAL.DEFAULT_FAIL_RESPONSE); + if (ERROR_LOG === true) { logger.write('[ERROR] initializeProductPlotter -> onProductStorageInitialized -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initializeProductPlotter -> err = ' + err) } + callBack(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function onProductCardStatusChanged(pProductCard) { - - if (INFO_LOG === true) { logger.write("[INFO] onProductCardStatusChanged -> Entering function."); } - - if (pProductCard.status === PRODUCT_CARD_STATUS.LOADING) { + function onProductCardStatusChanged (pProductCard) { + if (INFO_LOG === true) { logger.write('[INFO] onProductCardStatusChanged -> Entering function.') } + if (pProductCard.status === PRODUCT_CARD_STATUS.LOADING) { /* Lets see if we can find the Plotter of this card on our Active Plotters list, other wise we will initialize it */ - let found = false; + let found = false - for (let i = 0; i < productPlotters.length; i++) { + for (let i = 0; i < productPlotters.length; i++) { + if (productPlotters[i].productCard.code === pProductCard.code) { + found = true + } + } - if (productPlotters[i].productCard.code === pProductCard.code) { + if (found === false) { + initializeProductPlotter(pProductCard, onProductPlotterInitialized) - found = true; - - } - - } - - if (found === false) { - - initializeProductPlotter(pProductCard, onProductPlotterInitialized); - - function onProductPlotterInitialized(err) { - - if (INFO_LOG === true) { logger.write("[INFO] initializeProductPlotters -> onProductPlotterInitialized -> Entering function."); } + function onProductPlotterInitialized (err) { + if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotters -> onProductPlotterInitialized -> Entering function.') } /* There is no policy yet of what to do if this fails. */ - - } - } } + } + } - if (pProductCard.status === PRODUCT_CARD_STATUS.OFF) { - + if (pProductCard.status === PRODUCT_CARD_STATUS.OFF) { /* If the plotter of this card is on our Active Plotters list, then we remove it. */ - for (let i = 0; i < productPlotters.length; i++) { - - if (productPlotters[i].productCard.code === pProductCard.code) { - - if (productPlotters[i].profile !== undefined) { - - canvas.floatingSpace.profileBalls.destroyProfileBall(productPlotters[i].profile); - - } + for (let i = 0; i < productPlotters.length; i++) { + if (productPlotters[i].productCard.code === pProductCard.code) { + if (productPlotters[i].profile !== undefined) { + canvas.floatingSpace.profileBalls.destroyProfileBall(productPlotters[i].profile) + } /* Destroyd the Note Set */ - canvas.floatingSpace.noteSets.destroyNoteSet(productPlotters[i].noteSet); + canvas.floatingSpace.noteSets.destroyNoteSet(productPlotters[i].noteSet) /* Then the panels. */ - for (let j = 0; j < productPlotters[i].panels.length; j++) { - - canvas.panelsSpace.destroyPanel(productPlotters[i].panels[j]); - - } + for (let j = 0; j < productPlotters[i].panels.length; j++) { + canvas.panelsSpace.destroyPanel(productPlotters[i].panels[j]) + } /* Finally the Storage Objects */ - productPlotters[i].storage.finalize(); + productPlotters[i].storage.finalize() - if (productPlotters[i].plotter.finalize !== undefined) { + if (productPlotters[i].plotter.finalize !== undefined) { + productPlotters[i].plotter.finalize() + } - productPlotters[i].plotter.finalize(); + productPlotters.splice(i, 1) // Delete item from array. - } - - productPlotters.splice(i, 1); // Delete item from array. - - return; // We already found the product woth changes and processed it. - } - } + return // We already found the product woth changes and processed it. } + } + } + } + + function setTimePeriod (pTimePeriod) { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> Entering function.') } + + timePeriod = pTimePeriod + + if (initializationReady === true) { + for (let i = 0; i < productPlotters.length; i++) { + let productPlotter = productPlotters[i] + + productPlotter.productCard.setTimePeriod(timePeriod) + productPlotter.storage.setTimePeriod(timePeriod) + productPlotter.plotter.setTimePeriod(timePeriod) + } + + for (let i = 0; i < competitionPlotters.length; i++) { + let competitionPlotter = competitionPlotters[i] + + competitionPlotter.plotter.setTimePeriod(timePeriod) + } + } + } + + function setDatetime (pDatetime) { + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> Entering function.') } + + datetime = pDatetime + + for (let i = 0; i < productPlotters.length; i++) { + let productPlotter = productPlotters[i] + + productPlotter.productCard.setDatetime(pDatetime) + productPlotter.storage.setDatetime(pDatetime) + productPlotter.plotter.setDatetime(pDatetime) } - function setTimePeriod(pTimePeriod) { + for (let i = 0; i < competitionPlotters.length; i++) { + let competitionPlotter = competitionPlotters[i] - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> Entering function."); } - - timePeriod = pTimePeriod; - - if (initializationReady === true) { - - for (let i = 0; i < productPlotters.length; i++) { - - let productPlotter = productPlotters[i]; - - productPlotter.productCard.setTimePeriod(timePeriod); - productPlotter.storage.setTimePeriod(timePeriod); - productPlotter.plotter.setTimePeriod(timePeriod); - - } - - for (let i = 0; i < competitionPlotters.length; i++) { - - let competitionPlotter = competitionPlotters[i]; - - competitionPlotter.plotter.setTimePeriod(timePeriod); - - } - } + competitionPlotter.plotter.setDatetime(datetime) } + } - function setDatetime(pDatetime) { + function positionAtDatetime (pDatetime) { + if (INFO_LOG === true) { logger.write('[INFO] positionAtDatetime -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> Entering function."); } + for (let i = 0; i < productPlotters.length; i++) { + let productPlotter = productPlotters[i] - datetime = pDatetime; - - for (let i = 0; i < productPlotters.length; i++) { - - let productPlotter = productPlotters[i]; - - productPlotter.productCard.setDatetime(pDatetime); - productPlotter.storage.setDatetime(pDatetime); - productPlotter.plotter.setDatetime(pDatetime); - - } - - for (let i = 0; i < competitionPlotters.length; i++) { - - let competitionPlotter = competitionPlotters[i]; - - competitionPlotter.plotter.setDatetime(datetime); - - } + if (productPlotter.plotter.positionAtDatetime !== undefined) { + productPlotter.plotter.positionAtDatetime(pDatetime) + } } + } - function positionAtDatetime(pDatetime) { + function getContainer (point) { + if (INFO_LOG === true) { logger.write('[INFO] getContainer -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] positionAtDatetime -> Entering function."); } + let container - for (let i = 0; i < productPlotters.length; i++) { + return container + } - let productPlotter = productPlotters[i]; + function draw () { + if (INTENSIVE_LOG === true) { logger.write('[INFO] draw -> Entering function.') } - if (productPlotter.plotter.positionAtDatetime !== undefined) { - productPlotter.plotter.positionAtDatetime(pDatetime); - } - - } - } - - function getContainer(point) { - - if (INFO_LOG === true) { logger.write("[INFO] getContainer -> Entering function."); } - - let container; - - return container; - } - - function draw() { - - if (INTENSIVE_LOG === true) { logger.write("[INFO] draw -> Entering function."); } - - if (productPlotters === undefined) { return; } // We need to wait + if (productPlotters === undefined) { return } // We need to wait /* First the Product Plotters. */ - for (let i = 0; i < productPlotters.length; i++) { - - let productPlotter = productPlotters[i]; - productPlotter.plotter.draw(); - - } + for (let i = 0; i < productPlotters.length; i++) { + let productPlotter = productPlotters[i] + productPlotter.plotter.draw() + } /* Then the competition plotters. */ - for (let i = 0; i < competitionPlotters.length; i++) { - - let competitionPlotter = competitionPlotters[i]; - competitionPlotter.plotter.draw(); - } + for (let i = 0; i < competitionPlotters.length; i++) { + let competitionPlotter = competitionPlotters[i] + competitionPlotter.plotter.draw() } + } } diff --git a/ProductCard.js b/ProductCard.js index 025dfcb27..7ef21a7f0 100644 --- a/ProductCard.js +++ b/ProductCard.js @@ -1,70 +1,69 @@ -function newProductCard() { + function newProductCard () { + const CONSOLE_LOG = false - const CONSOLE_LOG = false; + var thisObject = { + container: undefined, + draw: draw, + status: 'off', + devTeam: undefined, + bot: undefined, + product: undefined, + code: undefined, - var thisObject = { - container: undefined, - draw: draw, - status: 'off', - devTeam: undefined, - bot: undefined, - product: undefined, - code: undefined, + setDatetime: setDatetime, + setTimePeriod: setTimePeriod, - setDatetime: setDatetime, - setTimePeriod: setTimePeriod, + onMarketFileLoaded: onMarketFileLoaded, + onDailyFileLoaded: onDailyFileLoaded, + onSingleFileLoaded: onSingleFileLoaded, + onFileSequenceLoaded: onFileSequenceLoaded, - onMarketFileLoaded: onMarketFileLoaded, - onDailyFileLoaded: onDailyFileLoaded, - onSingleFileLoaded: onSingleFileLoaded, - onFileSequenceLoaded: onFileSequenceLoaded, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + let LOADING_FILL_STYLE = 'rgba(234, 143, 23, @Opacity)' + let LOADED_FILL_STYLE = 'rgba(45, 232, 28, @Opacity)' + let UNLOADED_FILL_STYLE = 'rgba(226, 226, 226, @Opacity)' - let LOADING_FILL_STYLE = 'rgba(234, 143, 23, @Opacity)'; - let LOADED_FILL_STYLE = 'rgba(45, 232, 28, @Opacity)'; - let UNLOADED_FILL_STYLE = 'rgba(226, 226, 226, @Opacity)'; + let LOADING_STROKE_STYLE = 'rgba(234, 143, 23, @Opacity)' + let LOADED_STROKE_STYLE = 'rgba(150, 150, 150, @Opacity)' + let UNLOADED_STROKE_STYLE = 'rgba(226, 226, 226, @Opacity)' - let LOADING_STROKE_STYLE = 'rgba(234, 143, 23, @Opacity)'; - let LOADED_STROKE_STYLE = 'rgba(150, 150, 150, @Opacity)'; - let UNLOADED_STROKE_STYLE = 'rgba(226, 226, 226, @Opacity)'; + let marketFileProgressBar = { + value: 0, + animatedValue: 0, + fillStyle: UNLOADED_FILL_STYLE, + strokeStyle: UNLOADED_STROKE_STYLE, + opacity: 0.00 + } - let marketFileProgressBar = { - value: 0, - animatedValue: 0, - fillStyle: UNLOADED_FILL_STYLE, - strokeStyle: UNLOADED_STROKE_STYLE, - opacity: 0.00 - }; + let dailyFileProgressBar = { + value: 0, + animatedValue: 0, + fillStyle: UNLOADED_FILL_STYLE, + strokeStyle: UNLOADED_STROKE_STYLE, + opacity: 0.00 + } - let dailyFileProgressBar = { - value: 0, - animatedValue: 0, - fillStyle: UNLOADED_FILL_STYLE, - strokeStyle: UNLOADED_STROKE_STYLE, - opacity: 0.00 - }; + let singleFileProgressBar = { + value: 0, + animatedValue: 0, + fillStyle: UNLOADED_FILL_STYLE, + strokeStyle: UNLOADED_STROKE_STYLE, + opacity: 0.00 + } - let singleFileProgressBar = { - value: 0, - animatedValue: 0, - fillStyle: UNLOADED_FILL_STYLE, - strokeStyle: UNLOADED_STROKE_STYLE, - opacity: 0.00 - }; + let fileSequenceProgressBar = { + value: 0, + animatedValue: 0, + fillStyle: UNLOADED_FILL_STYLE, + strokeStyle: UNLOADED_STROKE_STYLE, + opacity: 0.00 + } - let fileSequenceProgressBar = { - value: 0, - animatedValue: 0, - fillStyle: UNLOADED_FILL_STYLE, - strokeStyle: UNLOADED_STROKE_STYLE, - opacity: 0.00 - }; - - let timePeriod = INITIAL_TIME_PERIOD; - let datetime = INITIAL_DATE; + let timePeriod = INITIAL_TIME_PERIOD + let datetime = INITIAL_DATE /* TODO We are in a transition period in which bots and teams images might be located at different places. What we are going to do then is to try to load them from both places and use the variable that finally gets an @@ -72,214 +71,193 @@ /* This is the legacy image storage. */ - let legacyTeamAvatar; - let legacyTeamAvatarLoaded = false; + let legacyTeamAvatar + let legacyTeamAvatarLoaded = false /* TODO Temporary code */ - let legacyBotAvatar; - let legacyBotAvatarLoaded = false; + let legacyBotAvatar + let legacyBotAvatarLoaded = false /* Now the plotters images */ - let legacyPlotterBanner; - let legacyPlotterBannerLoaded = false; + let legacyPlotterBanner + let legacyPlotterBannerLoaded = false /* We are transitioning towards this */ - let teamAvatar; // stores the avatar image of the team the bot portrayed at this card belongs to. - let teamAvatarLoaded = false; + let teamAvatar // stores the avatar image of the team the bot portrayed at this card belongs to. + let teamAvatarLoaded = false /* TODO Temporary code */ - let botAvatar; // stores the avatar image of the team the bot portrayed at this card belongs to. - let botAvatarLoaded = false; + let botAvatar // stores the avatar image of the team the bot portrayed at this card belongs to. + let botAvatarLoaded = false /* Add an Event Handler */ - thisObject.eventHandler = newEventHandler(); - let imagesLoaded = 0; + thisObject.eventHandler = newEventHandler() + let imagesLoaded = 0 - return thisObject; - - function initialize() { + return thisObject + function initialize () { /* Create this objects continer */ - var container = newContainer(); - container.name = "Product Card " + thisObject.code; - container.initialize(); - container.isDraggeable = false; - container.isClickeable = true; - thisObject.container = container; + var container = newContainer() + container.name = 'Product Card ' + thisObject.code + container.initialize() + container.isDraggeable = false + container.isClickeable = true + thisObject.container = container - /* Add information that will later be needed.*/ + /* Add information that will later be needed. */ - let team = ecosystem.getTeam(thisObject.product.plotter.devTeam); - let plotter = ecosystem.getPlotter(team, thisObject.product.plotter.codeName); - let plotterModule = ecosystem.getPlotterModule(plotter, thisObject.product.plotter.moduleName); + let team = ecosystem.getTeam(thisObject.product.plotter.devTeam) + let plotter = ecosystem.getPlotter(team, thisObject.product.plotter.codeName) + let plotterModule = ecosystem.getPlotterModule(plotter, thisObject.product.plotter.moduleName) - thisObject.product.plotter.profilePicture = plotterModule.profilePicture; - thisObject.product.plotter.module = plotterModule; + thisObject.product.plotter.profilePicture = plotterModule.profilePicture + thisObject.product.plotter.module = plotterModule /* Lets set the basic dimensions of this thisObject. */ - var position = { - x: 0, - y: 0 - }; + var position = { + x: 0, + y: 0 + } - this.container.frame.position = position; - this.container.frame.width = 330; - this.container.frame.height = 100; + this.container.frame.position = position + this.container.frame.width = 330 + this.container.frame.height = 100 /* We retrieve the locally stored status of the Product */ - let storedValue = window.localStorage.getItem(thisObject.code); + let storedValue = window.localStorage.getItem(thisObject.code) - if (storedValue !== null) { - - thisObject.status = storedValue; - - if (thisObject.status === PRODUCT_CARD_STATUS.ON) { - - changeStatusTo(PRODUCT_CARD_STATUS.LOADING); - - } - - } else { + if (storedValue !== null) { + thisObject.status = storedValue + if (thisObject.status === PRODUCT_CARD_STATUS.ON) { + changeStatusTo(PRODUCT_CARD_STATUS.LOADING) + } + } else { /* This happens the first time the app is run on a new browser. We will start with all product off, except for the candles chart, since something needs to be shown and allow the user to position themselves - on the timeline. + on the timeline. For the time being, we will hard-code the name of the bot we will turn on by default, since we dont see that change in the near future. */ - const DEFAULT_ON_PRODUCT = "AAMasters-AAOlivia-Candles"; + const DEFAULT_ON_PRODUCT = 'AAMasters-AAOlivia-Candles' - if (thisObject.code === DEFAULT_ON_PRODUCT) { - - changeStatusTo(PRODUCT_CARD_STATUS.LOADING); - - } else { - - changeStatusTo(PRODUCT_CARD_STATUS.OFF); - - } - } + if (thisObject.code === DEFAULT_ON_PRODUCT) { + changeStatusTo(PRODUCT_CARD_STATUS.LOADING) + } else { + changeStatusTo(PRODUCT_CARD_STATUS.OFF) + } + } /* Lets listen to our own events to react when we have a Mouse Click */ - thisObject.container.eventHandler.listenToEvent('onMouseClick', buttonPressed); - + thisObject.container.eventHandler.listenToEvent('onMouseClick', buttonPressed) /* WARNING THIS IS TEMPORARY CODE */ - const LEGACY_TEAM = thisObject.devTeam.codeName; - const REPO = thisObject.bot.repo; - const PROFILE_PIC = thisObject.bot.profilePicture; + const LEGACY_TEAM = thisObject.devTeam.codeName + const REPO = thisObject.bot.repo + const PROFILE_PIC = thisObject.bot.profilePicture /* The plotter banner, comes from the Legacy Location so far, no matter if the Team is at the Teams Modules or not. */ - const PLOTTER_TEAM = thisObject.product.plotter.devTeam; - const PLOTTER_REPO = thisObject.product.plotter.codeName; - const PLOTTER_PROFILE_PIC = thisObject.product.plotter.profilePicture; + const PLOTTER_TEAM = thisObject.product.plotter.devTeam + const PLOTTER_REPO = thisObject.product.plotter.codeName + const PLOTTER_PROFILE_PIC = thisObject.product.plotter.profilePicture - legacyPlotterBanner = new Image(); - legacyPlotterBanner.onload = onLegacyPlotterBanner; + legacyPlotterBanner = new Image() + legacyPlotterBanner.onload = onLegacyPlotterBanner - function onLegacyPlotterBanner() { - legacyPlotterBannerLoaded = true; - } + function onLegacyPlotterBanner () { + legacyPlotterBannerLoaded = true + } - legacyPlotterBanner.src = window.canvasApp.urlPrefix + "Images/" + PLOTTER_TEAM + "/" + PLOTTER_REPO + "/" + PLOTTER_PROFILE_PIC; + legacyPlotterBanner.src = window.canvasApp.urlPrefix + 'Images/' + PLOTTER_TEAM + '/' + PLOTTER_REPO + '/' + PLOTTER_PROFILE_PIC - const TEAM = thisObject.devTeam.codeName.toLowerCase(); - const BOT = thisObject.bot.codeName.toLowerCase(); + const TEAM = thisObject.devTeam.codeName.toLowerCase() + const BOT = thisObject.bot.codeName.toLowerCase() - if (window.canvasApp.context.teamProfileImages.get(TEAM) === undefined) { // This means this Team is a Lecay Team, still not at any Module. + if (window.canvasApp.context.teamProfileImages.get(TEAM) === undefined) { + // This means this Team is a Lecay Team, still not at any Module. /* Here we will download the images still at the legacy storage. */ - legacyTeamAvatar = new Image(); + legacyTeamAvatar = new Image() - legacyTeamAvatar.onload = onLegacyImageLoad; + legacyTeamAvatar.onload = onLegacyImageLoad - function onLegacyImageLoad() { - legacyTeamAvatarLoaded = true; - } + function onLegacyImageLoad () { + legacyTeamAvatarLoaded = true + } - legacyTeamAvatar.src = window.canvasApp.urlPrefix + "Images/" + LEGACY_TEAM + "/" + LEGACY_TEAM + ".png"; + legacyTeamAvatar.src = window.canvasApp.urlPrefix + 'Images/' + LEGACY_TEAM + '/' + LEGACY_TEAM + '.png' - legacyBotAvatar = new Image(); - legacyBotAvatar.onload = onLegacyImageLoadBot; + legacyBotAvatar = new Image() + legacyBotAvatar.onload = onLegacyImageLoadBot - function onLegacyImageLoadBot() { - legacyBotAvatarLoaded = true; - thisObject.bot.avatar = legacyBotAvatar; - } + function onLegacyImageLoadBot () { + legacyBotAvatarLoaded = true + thisObject.bot.avatar = legacyBotAvatar + } - legacyBotAvatar.src = window.canvasApp.urlPrefix + "Images/" + LEGACY_TEAM + "/" + REPO + "/" + PROFILE_PIC; - - } - - else { - - /* + legacyBotAvatar.src = window.canvasApp.urlPrefix + 'Images/' + LEGACY_TEAM + '/' + REPO + '/' + PROFILE_PIC + } else { + /* Here we will download the images of teams uploaded at the Teams Module. There might be Product Cards of bots beloging to teams not present currently at the Teams Module, in those cases nothing should happen. */ - teamAvatar = new Image(); + teamAvatar = new Image() - teamAvatar.onload = onImageLoad; + teamAvatar.onload = onImageLoad - function onImageLoad() { - teamAvatarLoaded = true; - } + function onImageLoad () { + teamAvatarLoaded = true + } - teamAvatar.src = window.canvasApp.context.teamProfileImages.get(TEAM); + teamAvatar.src = window.canvasApp.context.teamProfileImages.get(TEAM) - botAvatar = new Image(); - botAvatar.onload = onImageLoadBot; + botAvatar = new Image() + botAvatar.onload = onImageLoadBot - function onImageLoadBot() { - botAvatarLoaded = true; - thisObject.bot.avatar = botAvatar; - } + function onImageLoadBot () { + botAvatarLoaded = true + thisObject.bot.avatar = botAvatar + } - botAvatar.src = window.canvasApp.context.fbProfileImages.get(TEAM + "-" + BOT); + botAvatar.src = window.canvasApp.context.fbProfileImages.get(TEAM + '-' + BOT) + } + } - } - } - - function getContainer(point) { - - var container; + function getContainer (point) { + var container /* First we check if this point is inside this space. */ - if (this.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (this.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - - } - - function setDatetime(pDatetime) { + return undefined + } + } + function setDatetime (pDatetime) { /* When the datetime changes from one day to another, this forces cursors to potentially load more files, thus we reset this counter and @@ -287,28 +265,23 @@ */ - let currentDate = Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS); - let newDate = Math.trunc(pDatetime.valueOf() / ONE_DAY_IN_MILISECONDS); + let currentDate = Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS) + let newDate = Math.trunc(pDatetime.valueOf() / ONE_DAY_IN_MILISECONDS) - datetime = pDatetime; + datetime = pDatetime - if (currentDate !== newDate) { + if (currentDate !== newDate) { + if (timePeriod <= _1_HOUR_IN_MILISECONDS) { + dailyFileProgressBar.animatedValue = 0 - if (timePeriod <= _1_HOUR_IN_MILISECONDS) { - - dailyFileProgressBar.animatedValue = 0; - - if (CONSOLE_LOG === true) { - - console.log("ProductCard -> onDayChanged -> dailyFileProgressBar.animatedValue = " + dailyFileProgressBar.animatedValue); - - } - } - } - } - - function setTimePeriod(pTimePeriod) { + if (CONSOLE_LOG === true) { + console.log('ProductCard -> onDayChanged -> dailyFileProgressBar.animatedValue = ' + dailyFileProgressBar.animatedValue) + } + } + } + } + function setTimePeriod (pTimePeriod) { /* When the time period below or equal to 1 hour changes, this forces cursors to potentially load more files, thus we reset this counter and @@ -316,661 +289,617 @@ */ - if (timePeriod !== pTimePeriod) { + if (timePeriod !== pTimePeriod) { + timePeriod = pTimePeriod - timePeriod = pTimePeriod; + if (timePeriod <= _1_HOUR_IN_MILISECONDS) { + dailyFileProgressBar.animatedValue = 0 - if (timePeriod <= _1_HOUR_IN_MILISECONDS) { + if (CONSOLE_LOG === true) { + console.log('ProductCard -> onTimePeriodChanged -> dailyFileProgressBar.animatedValue = ' + dailyFileProgressBar.animatedValue) + } + } + } + } - dailyFileProgressBar.animatedValue = 0; + function onMarketFileLoaded (event) { + marketFileProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue) + marketFileProgressBar.fillStyle = LOADING_FILL_STYLE + marketFileProgressBar.strokeStyle = LOADING_STROKE_STYLE - if (CONSOLE_LOG === true) { + if (marketFileProgressBar.value > 100) { marketFileProgressBar.value = 100 } - console.log("ProductCard -> onTimePeriodChanged -> dailyFileProgressBar.animatedValue = " + dailyFileProgressBar.animatedValue); + if (CONSOLE_LOG === true) { + console.log('ProductCard onMarketFileLoaded Value = ' + marketFileProgressBar.value + '% for ' + thisObject.code + '. Event = ' + JSON.stringify(event)) + } + } - } - } - } - } + function onDailyFileLoaded (event) { + dailyFileProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue) + dailyFileProgressBar.fillStyle = LOADING_FILL_STYLE + dailyFileProgressBar.strokeStyle = LOADING_STROKE_STYLE - function onMarketFileLoaded(event) { + if (dailyFileProgressBar.value > 100) { dailyFileProgressBar.value = 100 } - marketFileProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue); - marketFileProgressBar.fillStyle = LOADING_FILL_STYLE; - marketFileProgressBar.strokeStyle = LOADING_STROKE_STYLE; + if (CONSOLE_LOG === true) { + console.log('ProductCard onDailyFileLoaded Value = ' + dailyFileProgressBar.value + '% for ' + thisObject.code + '. Event = ' + JSON.stringify(event)) + } + } - if (marketFileProgressBar.value > 100) { marketFileProgressBar.value = 100; } + function onSingleFileLoaded (event) { + singleFileProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue) + singleFileProgressBar.fillStyle = LOADING_FILL_STYLE + singleFileProgressBar.strokeStyle = LOADING_STROKE_STYLE - if (CONSOLE_LOG === true) { + if (singleFileProgressBar.value > 100) { singleFileProgressBar.value = 100 } - console.log("ProductCard onMarketFileLoaded Value = " + marketFileProgressBar.value + "% for " + thisObject.code + ". Event = " + JSON.stringify(event)); + if (CONSOLE_LOG === true) { + console.log('ProductCard onSingleFileLoaded Value = ' + singleFileProgressBar.value + '% for ' + thisObject.code + '. Event = ' + JSON.stringify(event)) + } + } - } - } + function onFileSequenceLoaded (event) { + fileSequenceProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue) + fileSequenceProgressBar.fillStyle = LOADING_FILL_STYLE + fileSequenceProgressBar.strokeStyle = LOADING_STROKE_STYLE - function onDailyFileLoaded(event) { + if (fileSequenceProgressBar.value > 100) { fileSequenceProgressBar.value = 100 } - dailyFileProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue); - dailyFileProgressBar.fillStyle = LOADING_FILL_STYLE; - dailyFileProgressBar.strokeStyle = LOADING_STROKE_STYLE; + if (CONSOLE_LOG === true) { + console.log('ProductCard onFileSequenceLoaded Value = ' + fileSequenceProgressBar.value + '% for ' + thisObject.code + '. Event = ' + JSON.stringify(event)) + } + } - if (dailyFileProgressBar.value > 100) { dailyFileProgressBar.value = 100;} + function buttonPressed (event) { + switch (thisObject.status) { - if (CONSOLE_LOG === true) { + case PRODUCT_CARD_STATUS.ON: - console.log("ProductCard onDailyFileLoaded Value = " + dailyFileProgressBar.value + "% for " + thisObject.code + ". Event = " + JSON.stringify(event)); + changeStatusTo(PRODUCT_CARD_STATUS.OFF) - } - } + marketFileProgressBar.animatedValue = 0 + marketFileProgressBar.value = 0 + marketFileProgressBar.fillStyle = UNLOADED_FILL_STYLE + marketFileProgressBar.strokeStyle = UNLOADED_STROKE_STYLE - function onSingleFileLoaded(event) { + dailyFileProgressBar.animatedValue = 0 + dailyFileProgressBar.value = 0 + dailyFileProgressBar.fillStyle = UNLOADED_FILL_STYLE + dailyFileProgressBar.strokeStyle = UNLOADED_STROKE_STYLE - singleFileProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue); - singleFileProgressBar.fillStyle = LOADING_FILL_STYLE; - singleFileProgressBar.strokeStyle = LOADING_STROKE_STYLE; + singleFileProgressBar.animatedValue = 0 + singleFileProgressBar.value = 0 + singleFileProgressBar.fillStyle = UNLOADED_FILL_STYLE + singleFileProgressBar.strokeStyle = UNLOADED_STROKE_STYLE - if (singleFileProgressBar.value > 100) { singleFileProgressBar.value = 100; } + fileSequenceProgressBar.animatedValue = 0 + fileSequenceProgressBar.value = 0 + fileSequenceProgressBar.fillStyle = UNLOADED_FILL_STYLE + fileSequenceProgressBar.strokeStyle = UNLOADED_STROKE_STYLE - if (CONSOLE_LOG === true) { + break - console.log("ProductCard onSingleFileLoaded Value = " + singleFileProgressBar.value + "% for " + thisObject.code + ". Event = " + JSON.stringify(event)); + case PRODUCT_CARD_STATUS.OFF: - } - } + changeStatusTo(PRODUCT_CARD_STATUS.LOADING) - function onFileSequenceLoaded(event) { + break - fileSequenceProgressBar.value = Math.trunc(event.currentValue * 100 / event.totalValue); - fileSequenceProgressBar.fillStyle = LOADING_FILL_STYLE; - fileSequenceProgressBar.strokeStyle = LOADING_STROKE_STYLE; + } + } - if (fileSequenceProgressBar.value > 100) { fileSequenceProgressBar.value = 100; } + function changeStatusTo (pNewStatus) { + if (thisObject.status !== pNewStatus) { + thisObject.status = pNewStatus - if (CONSOLE_LOG === true) { + let eventData = thisObject - console.log("ProductCard onFileSequenceLoaded Value = " + fileSequenceProgressBar.value + "% for " + thisObject.code + ". Event = " + JSON.stringify(event)); + thisObject.container.eventHandler.raiseEvent('Status Changed', eventData) - } - } + window.localStorage.setItem(thisObject.code, thisObject.status) + } + } - function buttonPressed(event) { - - switch (thisObject.status) { - - case PRODUCT_CARD_STATUS.ON: - - changeStatusTo(PRODUCT_CARD_STATUS.OFF); - - marketFileProgressBar.animatedValue = 0; - marketFileProgressBar.value = 0; - marketFileProgressBar.fillStyle = UNLOADED_FILL_STYLE; - marketFileProgressBar.strokeStyle = UNLOADED_STROKE_STYLE; - - dailyFileProgressBar.animatedValue = 0; - dailyFileProgressBar.value = 0; - dailyFileProgressBar.fillStyle = UNLOADED_FILL_STYLE; - dailyFileProgressBar.strokeStyle = UNLOADED_STROKE_STYLE; - - singleFileProgressBar.animatedValue = 0; - singleFileProgressBar.value = 0; - singleFileProgressBar.fillStyle = UNLOADED_FILL_STYLE; - singleFileProgressBar.strokeStyle = UNLOADED_STROKE_STYLE; - - fileSequenceProgressBar.animatedValue = 0; - fileSequenceProgressBar.value = 0; - fileSequenceProgressBar.fillStyle = UNLOADED_FILL_STYLE; - fileSequenceProgressBar.strokeStyle = UNLOADED_STROKE_STYLE; - - break; - - case PRODUCT_CARD_STATUS.OFF: - - changeStatusTo(PRODUCT_CARD_STATUS.LOADING); - - break; - - } - } - - function changeStatusTo(pNewStatus) { - - if (thisObject.status !== pNewStatus) { - - thisObject.status = pNewStatus; - - let eventData = thisObject; - - thisObject.container.eventHandler.raiseEvent('Status Changed', eventData); - - window.localStorage.setItem(thisObject.code, thisObject.status); - - } - } - - function draw() { - - drawProductCard(); - - } - - function drawProductCard() { + function draw () { + drawProductCard() + } + function drawProductCard () { /* Put images on the card. */ - const devTeamImageSize = 50; - const botImageSize = 50; - const plotterImageSize = { - width: 180, - height: 50 - }; + const devTeamImageSize = 50 + const botImageSize = 50 + const plotterImageSize = { + width: 180, + height: 50 + } /* First the Dev Team Profile Picture. */ - let teamImagePoint = { - x: 10, - y: thisObject.container.frame.height / 2 - devTeamImageSize / 2 - }; + let teamImagePoint = { + x: 10, + y: thisObject.container.frame.height / 2 - devTeamImageSize / 2 + } - teamImagePoint = thisObject.container.frame.frameThisPoint(teamImagePoint); + teamImagePoint = thisObject.container.frame.frameThisPoint(teamImagePoint) - let teamImage; + let teamImage - if (legacyTeamAvatarLoaded === true) { - teamImage = legacyTeamAvatar; - } + if (legacyTeamAvatarLoaded === true) { + teamImage = legacyTeamAvatar + } - if (teamAvatarLoaded === true) { - teamImage = teamAvatar; - } - - if (teamImage !== undefined) { - if (teamImage.naturalHeight !== 0) { + if (teamAvatarLoaded === true) { + teamImage = teamAvatar + } + if (teamImage !== undefined) { + if (teamImage.naturalHeight !== 0) { /* The image is rounded before being displayed. */ - browserCanvasContext.save(); - browserCanvasContext.beginPath(); - browserCanvasContext.arc(teamImagePoint.x + devTeamImageSize / 2, teamImagePoint.y + devTeamImageSize / 2, devTeamImageSize / 2, 0, Math.PI * 2, true); - browserCanvasContext.closePath(); - browserCanvasContext.clip(); - browserCanvasContext.drawImage(teamImage, teamImagePoint.x, teamImagePoint.y, devTeamImageSize, devTeamImageSize); - browserCanvasContext.beginPath(); - browserCanvasContext.arc(teamImagePoint.x, teamImagePoint.y, devTeamImageSize / 2, 0, Math.PI * 2, true); - browserCanvasContext.clip(); - browserCanvasContext.closePath(); - browserCanvasContext.restore(); - } - } - + browserCanvasContext.save() + browserCanvasContext.beginPath() + browserCanvasContext.arc(teamImagePoint.x + devTeamImageSize / 2, teamImagePoint.y + devTeamImageSize / 2, devTeamImageSize / 2, 0, Math.PI * 2, true) + browserCanvasContext.closePath() + browserCanvasContext.clip() + browserCanvasContext.drawImage(teamImage, teamImagePoint.x, teamImagePoint.y, devTeamImageSize, devTeamImageSize) + browserCanvasContext.beginPath() + browserCanvasContext.arc(teamImagePoint.x, teamImagePoint.y, devTeamImageSize / 2, 0, Math.PI * 2, true) + browserCanvasContext.clip() + browserCanvasContext.closePath() + browserCanvasContext.restore() + } + } /* Second the Bot's Profile Picture. */ - if (thisObject.bot.profilePicture !== undefined) { + if (thisObject.bot.profilePicture !== undefined) { + let botImagePoint = { + x: thisObject.container.frame.width - botImageSize / 2 - 40, + y: thisObject.container.frame.height / 2 - botImageSize / 2 + } - let botImagePoint = { - x: thisObject.container.frame.width - botImageSize / 2 - 40, - y: thisObject.container.frame.height / 2 - botImageSize / 2 - }; + botImagePoint = thisObject.container.frame.frameThisPoint(botImagePoint) - botImagePoint = thisObject.container.frame.frameThisPoint(botImagePoint); - - let imageId = thisObject.bot.devTeam + "." + thisObject.bot.profilePicture; + let imageId = thisObject.bot.devTeam + '.' + thisObject.bot.profilePicture /* TODO Temporary code */ - let botImage; - - botImage = thisObject.bot.avatar; - + let botImage - if (botImage !== undefined) { - if (botImage.naturalHeight !== 0) { + botImage = thisObject.bot.avatar + if (botImage !== undefined) { + if (botImage.naturalHeight !== 0) { /* The image is rounded before being displayed. */ - browserCanvasContext.save(); - browserCanvasContext.beginPath(); - browserCanvasContext.arc(botImagePoint.x + botImageSize / 2, botImagePoint.y + botImageSize / 2, botImageSize / 2, 0, Math.PI * 2, true); - browserCanvasContext.closePath(); - browserCanvasContext.clip(); - browserCanvasContext.drawImage(botImage, botImagePoint.x, botImagePoint.y, botImageSize, botImageSize); - browserCanvasContext.beginPath(); - browserCanvasContext.arc(botImagePoint.x, botImagePoint.y, botImageSize / 2, 0, Math.PI * 2, true); - browserCanvasContext.clip(); - browserCanvasContext.closePath(); - browserCanvasContext.restore(); - } - } - } + browserCanvasContext.save() + browserCanvasContext.beginPath() + browserCanvasContext.arc(botImagePoint.x + botImageSize / 2, botImagePoint.y + botImageSize / 2, botImageSize / 2, 0, Math.PI * 2, true) + browserCanvasContext.closePath() + browserCanvasContext.clip() + browserCanvasContext.drawImage(botImage, botImagePoint.x, botImagePoint.y, botImageSize, botImageSize) + browserCanvasContext.beginPath() + browserCanvasContext.arc(botImagePoint.x, botImagePoint.y, botImageSize / 2, 0, Math.PI * 2, true) + browserCanvasContext.clip() + browserCanvasContext.closePath() + browserCanvasContext.restore() + } + } + } /* Third the Plotter's Profile Picture. */ - if (thisObject.product.plotter.profilePicture !== undefined) { + if (thisObject.product.plotter.profilePicture !== undefined) { + let plotterImagePoint = { + x: thisObject.container.frame.width / 2 - plotterImageSize.width / 2, + y: thisObject.container.frame.height / 2 - plotterImageSize.height / 2 + } - let plotterImagePoint = { - x: thisObject.container.frame.width / 2 - plotterImageSize.width / 2, - y: thisObject.container.frame.height / 2 - plotterImageSize.height / 2 - }; + plotterImagePoint = thisObject.container.frame.frameThisPoint(plotterImagePoint) - plotterImagePoint = thisObject.container.frame.frameThisPoint(plotterImagePoint); + let imageId = thisObject.product.plotter.devTeam + '.' + thisObject.product.plotter.codeName + '.' + thisObject.product.plotter.moduleName + '.' + thisObject.product.plotter.profilePicture + let plotterImage = legacyPlotterBanner - let imageId = thisObject.product.plotter.devTeam + "." + thisObject.product.plotter.codeName + "." + thisObject.product.plotter.moduleName + "." + thisObject.product.plotter.profilePicture; - let plotterImage = legacyPlotterBanner; + if (plotterImage !== undefined) { + if (plotterImage.naturalHeight !== 0) { + browserCanvasContext.drawImage(plotterImage, plotterImagePoint.x, plotterImagePoint.y, plotterImageSize.width, plotterImageSize.height) + } + } + } - if (plotterImage !== undefined) { - if (plotterImage.naturalHeight !== 0) { - browserCanvasContext.drawImage(plotterImage, plotterImagePoint.x, plotterImagePoint.y, plotterImageSize.width, plotterImageSize.height); - } - } - } + drawProductLoadStatus() - drawProductLoadStatus(); - - function drawProductLoadStatus() { + function drawProductLoadStatus () { + let offFillStyle = 'rgba(' + UI_COLOR.RED + ', 0.20)' + let onFillStyle = 'rgba(' + UI_COLOR.GREEN + ', 0.20)' + let loadingFillStyle = 'rgba(' + UI_COLOR.TITANIUM_YELLOW + ', 0.40)' - let offFillStyle = 'rgba(' + UI_COLOR.RED + ', 0.20)'; - let onFillStyle = 'rgba(' + UI_COLOR.GREEN + ', 0.20)'; - let loadingFillStyle = 'rgba(' + UI_COLOR.TITANIUM_YELLOW + ', 0.40)'; + switch (thisObject.status) { - switch (thisObject.status) { + case PRODUCT_CARD_STATUS.ON: + browserCanvasContext.fillStyle = onFillStyle + break - case PRODUCT_CARD_STATUS.ON: - browserCanvasContext.fillStyle = onFillStyle; - break; + case PRODUCT_CARD_STATUS.OFF: + browserCanvasContext.fillStyle = offFillStyle + break - case PRODUCT_CARD_STATUS.OFF: - browserCanvasContext.fillStyle = offFillStyle; - break; + case PRODUCT_CARD_STATUS.LOADING: + browserCanvasContext.fillStyle = loadingFillStyle + break - case PRODUCT_CARD_STATUS.LOADING: - browserCanvasContext.fillStyle = loadingFillStyle; - break; + } - } + let centerPoint = { + x: thisObject.container.frame.width / 2, + y: thisObject.container.frame.height / 2 - 13 + } - let centerPoint = { - x: thisObject.container.frame.width / 2, - y: thisObject.container.frame.height / 2 - 13 - }; + let point1 = { + x: centerPoint.x - plotterImageSize.width / 2, + y: centerPoint.y - plotterImageSize.height / 2 - 7 + } - let point1 = { - x: centerPoint.x - plotterImageSize.width / 2, - y: centerPoint.y - plotterImageSize.height / 2 - 7 - }; + let point2 = { + x: centerPoint.x + plotterImageSize.width / 2, + y: centerPoint.y - plotterImageSize.height / 2 - 7 + } - let point2 = { - x: centerPoint.x + plotterImageSize.width / 2, - y: centerPoint.y - plotterImageSize.height / 2 - 7 - }; + let point3 = { + x: centerPoint.x + plotterImageSize.width / 2, + y: centerPoint.y - plotterImageSize.height / 2 + 7 + } - let point3 = { - x: centerPoint.x + plotterImageSize.width / 2, - y: centerPoint.y - plotterImageSize.height / 2 + 7 - }; - - let point4 = { - x: centerPoint.x - plotterImageSize.width / 2, - y: centerPoint.y - plotterImageSize.height / 2 + 7 - }; + let point4 = { + x: centerPoint.x - plotterImageSize.width / 2, + y: centerPoint.y - plotterImageSize.height / 2 + 7 + } /* Now the transformations. */ - point1 = thisObject.container.frame.frameThisPoint(point1); - point2 = thisObject.container.frame.frameThisPoint(point2); - point3 = thisObject.container.frame.frameThisPoint(point3); - point4 = thisObject.container.frame.frameThisPoint(point4); + point1 = thisObject.container.frame.frameThisPoint(point1) + point2 = thisObject.container.frame.frameThisPoint(point2) + point3 = thisObject.container.frame.frameThisPoint(point3) + point4 = thisObject.container.frame.frameThisPoint(point4) - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - browserCanvasContext.lineTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - browserCanvasContext.closePath(); + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + browserCanvasContext.lineTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + browserCanvasContext.closePath() - browserCanvasContext.fill(); + browserCanvasContext.fill() - browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)'; - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.stroke(); - - } + browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)' + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.stroke() + } /* print the text */ - let labelPoint; - let fontSize = 10; + let labelPoint + let fontSize = 10 - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY - let label; + let label /* devTeam */ - label = thisObject.devTeam.displayName; + label = thisObject.devTeam.displayName - labelPoint = { - x: 10 + devTeamImageSize / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: thisObject.container.frame.height / 2 + devTeamImageSize / 2 + fontSize * FONT_ASPECT_RATIO + 5 - }; + labelPoint = { + x: 10 + devTeamImageSize / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: thisObject.container.frame.height / 2 + devTeamImageSize / 2 + fontSize * FONT_ASPECT_RATIO + 5 + } - labelPoint = thisObject.container.frame.frameThisPoint(labelPoint); + labelPoint = thisObject.container.frame.frameThisPoint(labelPoint) - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) /* bot */ - label = thisObject.bot.displayName; + label = thisObject.bot.displayName - labelPoint = { - x: thisObject.container.frame.width - 40 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: thisObject.container.frame.height / 2 + devTeamImageSize / 2 + fontSize * FONT_ASPECT_RATIO + 5 - }; + labelPoint = { + x: thisObject.container.frame.width - 40 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: thisObject.container.frame.height / 2 + devTeamImageSize / 2 + fontSize * FONT_ASPECT_RATIO + 5 + } - labelPoint = thisObject.container.frame.frameThisPoint(labelPoint); + labelPoint = thisObject.container.frame.frameThisPoint(labelPoint) - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) /* product */ - fontSize = 10; + fontSize = 10 - label = thisObject.product.displayName; + label = thisObject.product.displayName - labelPoint = { - x: 65, - y: thisObject.container.frame.height / 2 + 15 - }; + labelPoint = { + x: 65, + y: thisObject.container.frame.height / 2 + 15 + } - labelPoint = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: thisObject.container.frame.height / 2 - devTeamImageSize / 2 - fontSize * FONT_ASPECT_RATIO - 5 - }; + labelPoint = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: thisObject.container.frame.height / 2 - devTeamImageSize / 2 - fontSize * FONT_ASPECT_RATIO - 5 + } - labelPoint = thisObject.container.frame.frameThisPoint(labelPoint); + labelPoint = thisObject.container.frame.frameThisPoint(labelPoint) - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) /* ------------------- Progress Bars -------------------------- */ - const ANIMATED_INCREMENT = 5; - const OPACITY_INCREMENT = 0.05; - const OPACITY_MIN = 0.1; + const ANIMATED_INCREMENT = 5 + const OPACITY_INCREMENT = 0.05 + const OPACITY_MIN = 0.1 - let point1; - let point2; - let point3; - let point4; + let point1 + let point2 + let point3 + let point4 /* We draw here the Market Progress Bar. */ /* Animate */ - if (marketFileProgressBar.animatedValue < marketFileProgressBar.value) { + if (marketFileProgressBar.animatedValue < marketFileProgressBar.value) { + marketFileProgressBar.animatedValue = marketFileProgressBar.animatedValue + ANIMATED_INCREMENT + marketFileProgressBar.opacity = marketFileProgressBar.opacity + OPACITY_INCREMENT + } - marketFileProgressBar.animatedValue = marketFileProgressBar.animatedValue + ANIMATED_INCREMENT; - marketFileProgressBar.opacity = marketFileProgressBar.opacity + OPACITY_INCREMENT; + if (marketFileProgressBar.animatedValue >= 100) { + marketFileProgressBar.animatedValue = 100 - } + marketFileProgressBar.opacity = marketFileProgressBar.opacity - OPACITY_INCREMENT + if (marketFileProgressBar.opacity < OPACITY_MIN) { marketFileProgressBar.opacity = OPACITY_MIN } - if (marketFileProgressBar.animatedValue >= 100) { + marketFileProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', marketFileProgressBar.opacity.toString()) + marketFileProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', marketFileProgressBar.opacity.toString()) - marketFileProgressBar.animatedValue = 100; + changeStatusTo(PRODUCT_CARD_STATUS.ON) + } - marketFileProgressBar.opacity = marketFileProgressBar.opacity - OPACITY_INCREMENT; - if (marketFileProgressBar.opacity < OPACITY_MIN) { marketFileProgressBar.opacity = OPACITY_MIN;} + point1 = { + x: 0, + y: thisObject.container.frame.height - 1 + } - marketFileProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', marketFileProgressBar.opacity.toString()); - marketFileProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', marketFileProgressBar.opacity.toString()); + point2 = { + x: thisObject.container.frame.width * marketFileProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 1 + } - changeStatusTo(PRODUCT_CARD_STATUS.ON); - } + point3 = { + x: thisObject.container.frame.width * marketFileProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 3 + } - point1 = { - x: 0, - y: thisObject.container.frame.height - 1 - }; - - point2 = { - x: thisObject.container.frame.width * marketFileProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 1 - }; - - point3 = { - x: thisObject.container.frame.width * marketFileProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 3 - }; - - point4 = { - x: 0, - y: thisObject.container.frame.height - 3 - }; + point4 = { + x: 0, + y: thisObject.container.frame.height - 3 + } /* Now the transformations. */ - point1 = thisObject.container.frame.frameThisPoint(point1); - point2 = thisObject.container.frame.frameThisPoint(point2); - point3 = thisObject.container.frame.frameThisPoint(point3); - point4 = thisObject.container.frame.frameThisPoint(point4); + point1 = thisObject.container.frame.frameThisPoint(point1) + point2 = thisObject.container.frame.frameThisPoint(point2) + point3 = thisObject.container.frame.frameThisPoint(point3) + point4 = thisObject.container.frame.frameThisPoint(point4) - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - browserCanvasContext.lineTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - browserCanvasContext.closePath(); + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + browserCanvasContext.lineTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + browserCanvasContext.closePath() - browserCanvasContext.fillStyle = marketFileProgressBar.fillStyle.replace('@Opacity', marketFileProgressBar.opacity.toString()); - browserCanvasContext.strokeStyle = marketFileProgressBar.strokeStyle.replace('@Opacity', marketFileProgressBar.opacity.toString()); + browserCanvasContext.fillStyle = marketFileProgressBar.fillStyle.replace('@Opacity', marketFileProgressBar.opacity.toString()) + browserCanvasContext.strokeStyle = marketFileProgressBar.strokeStyle.replace('@Opacity', marketFileProgressBar.opacity.toString()) - browserCanvasContext.fill(); - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.stroke(); + browserCanvasContext.fill() + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.stroke() /* We draw here the Daily Progress Bar. */ /* Animate */ - if (dailyFileProgressBar.animatedValue < dailyFileProgressBar.value) { + if (dailyFileProgressBar.animatedValue < dailyFileProgressBar.value) { + dailyFileProgressBar.animatedValue = dailyFileProgressBar.animatedValue + ANIMATED_INCREMENT + dailyFileProgressBar.opacity = dailyFileProgressBar.opacity + OPACITY_INCREMENT + } - dailyFileProgressBar.animatedValue = dailyFileProgressBar.animatedValue + ANIMATED_INCREMENT; - dailyFileProgressBar.opacity = dailyFileProgressBar.opacity + OPACITY_INCREMENT; + if (dailyFileProgressBar.animatedValue >= 100) { + dailyFileProgressBar.animatedValue = 100 - } + dailyFileProgressBar.opacity = dailyFileProgressBar.opacity - OPACITY_INCREMENT + if (dailyFileProgressBar.opacity < OPACITY_MIN) { dailyFileProgressBar.opacity = OPACITY_MIN } - if (dailyFileProgressBar.animatedValue >= 100) { + dailyFileProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', dailyFileProgressBar.opacity.toString()) + dailyFileProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', dailyFileProgressBar.opacity.toString()) - dailyFileProgressBar.animatedValue = 100; + changeStatusTo(PRODUCT_CARD_STATUS.ON) + } - dailyFileProgressBar.opacity = dailyFileProgressBar.opacity - OPACITY_INCREMENT; - if (dailyFileProgressBar.opacity < OPACITY_MIN) { dailyFileProgressBar.opacity = OPACITY_MIN; } + point1 = { + x: 0, + y: thisObject.container.frame.height - 4 + } - dailyFileProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', dailyFileProgressBar.opacity.toString()); - dailyFileProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', dailyFileProgressBar.opacity.toString()); + point2 = { + x: thisObject.container.frame.width * dailyFileProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 4 + } - changeStatusTo(PRODUCT_CARD_STATUS.ON); - } + point3 = { + x: thisObject.container.frame.width * dailyFileProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 6 + } - point1 = { - x: 0, - y: thisObject.container.frame.height - 4 - }; - - point2 = { - x: thisObject.container.frame.width * dailyFileProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 4 - }; - - point3 = { - x: thisObject.container.frame.width * dailyFileProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 6 - }; - - point4 = { - x: 0, - y: thisObject.container.frame.height - 6 - }; + point4 = { + x: 0, + y: thisObject.container.frame.height - 6 + } /* Now the transformations. */ - point1 = thisObject.container.frame.frameThisPoint(point1); - point2 = thisObject.container.frame.frameThisPoint(point2); - point3 = thisObject.container.frame.frameThisPoint(point3); - point4 = thisObject.container.frame.frameThisPoint(point4); + point1 = thisObject.container.frame.frameThisPoint(point1) + point2 = thisObject.container.frame.frameThisPoint(point2) + point3 = thisObject.container.frame.frameThisPoint(point3) + point4 = thisObject.container.frame.frameThisPoint(point4) - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - browserCanvasContext.lineTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - browserCanvasContext.closePath(); + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + browserCanvasContext.lineTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + browserCanvasContext.closePath() - browserCanvasContext.fillStyle = dailyFileProgressBar.fillStyle.replace('@Opacity', dailyFileProgressBar.opacity.toString()); - browserCanvasContext.strokeStyle = dailyFileProgressBar.strokeStyle.replace('@Opacity', dailyFileProgressBar.opacity.toString()); + browserCanvasContext.fillStyle = dailyFileProgressBar.fillStyle.replace('@Opacity', dailyFileProgressBar.opacity.toString()) + browserCanvasContext.strokeStyle = dailyFileProgressBar.strokeStyle.replace('@Opacity', dailyFileProgressBar.opacity.toString()) - browserCanvasContext.fill(); - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.stroke(); + browserCanvasContext.fill() + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.stroke() /* We draw here the Single File Progress Bar. */ /* Animate */ - if (singleFileProgressBar.animatedValue < singleFileProgressBar.value) { + if (singleFileProgressBar.animatedValue < singleFileProgressBar.value) { + singleFileProgressBar.animatedValue = singleFileProgressBar.animatedValue + ANIMATED_INCREMENT + singleFileProgressBar.opacity = singleFileProgressBar.opacity + OPACITY_INCREMENT + } - singleFileProgressBar.animatedValue = singleFileProgressBar.animatedValue + ANIMATED_INCREMENT; - singleFileProgressBar.opacity = singleFileProgressBar.opacity + OPACITY_INCREMENT; + if (singleFileProgressBar.animatedValue >= 100) { + singleFileProgressBar.animatedValue = 100 - } + singleFileProgressBar.opacity = singleFileProgressBar.opacity - OPACITY_INCREMENT + if (singleFileProgressBar.opacity < OPACITY_MIN) { singleFileProgressBar.opacity = OPACITY_MIN } - if (singleFileProgressBar.animatedValue >= 100) { + singleFileProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', singleFileProgressBar.opacity.toString()) + singleFileProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', singleFileProgressBar.opacity.toString()) - singleFileProgressBar.animatedValue = 100; + changeStatusTo(PRODUCT_CARD_STATUS.ON) + } - singleFileProgressBar.opacity = singleFileProgressBar.opacity - OPACITY_INCREMENT; - if (singleFileProgressBar.opacity < OPACITY_MIN) { singleFileProgressBar.opacity = OPACITY_MIN; } + point1 = { + x: 0, + y: thisObject.container.frame.height - 7 + } - singleFileProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', singleFileProgressBar.opacity.toString()); - singleFileProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', singleFileProgressBar.opacity.toString()); + point2 = { + x: thisObject.container.frame.width * singleFileProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 7 + } - changeStatusTo(PRODUCT_CARD_STATUS.ON); + point3 = { + x: thisObject.container.frame.width * singleFileProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 9 + } - } - - point1 = { - x: 0, - y: thisObject.container.frame.height - 7 - }; - - point2 = { - x: thisObject.container.frame.width * singleFileProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 7 - }; - - point3 = { - x: thisObject.container.frame.width * singleFileProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 9 - }; - - point4 = { - x: 0, - y: thisObject.container.frame.height - 9 - }; + point4 = { + x: 0, + y: thisObject.container.frame.height - 9 + } /* Now the transformations. */ - point1 = thisObject.container.frame.frameThisPoint(point1); - point2 = thisObject.container.frame.frameThisPoint(point2); - point3 = thisObject.container.frame.frameThisPoint(point3); - point4 = thisObject.container.frame.frameThisPoint(point4); + point1 = thisObject.container.frame.frameThisPoint(point1) + point2 = thisObject.container.frame.frameThisPoint(point2) + point3 = thisObject.container.frame.frameThisPoint(point3) + point4 = thisObject.container.frame.frameThisPoint(point4) - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - browserCanvasContext.lineTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - browserCanvasContext.closePath(); + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + browserCanvasContext.lineTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + browserCanvasContext.closePath() - browserCanvasContext.fillStyle = singleFileProgressBar.fillStyle.replace('@Opacity', singleFileProgressBar.opacity.toString()); - browserCanvasContext.strokeStyle = singleFileProgressBar.strokeStyle.replace('@Opacity', singleFileProgressBar.opacity.toString()); + browserCanvasContext.fillStyle = singleFileProgressBar.fillStyle.replace('@Opacity', singleFileProgressBar.opacity.toString()) + browserCanvasContext.strokeStyle = singleFileProgressBar.strokeStyle.replace('@Opacity', singleFileProgressBar.opacity.toString()) - browserCanvasContext.fill(); - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.stroke(); + browserCanvasContext.fill() + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.stroke() /* We draw here the File Sequence Progress Bar. */ /* Animate */ - if (fileSequenceProgressBar.animatedValue < fileSequenceProgressBar.value) { + if (fileSequenceProgressBar.animatedValue < fileSequenceProgressBar.value) { + fileSequenceProgressBar.animatedValue = fileSequenceProgressBar.animatedValue + ANIMATED_INCREMENT + fileSequenceProgressBar.opacity = fileSequenceProgressBar.opacity + OPACITY_INCREMENT + } - fileSequenceProgressBar.animatedValue = fileSequenceProgressBar.animatedValue + ANIMATED_INCREMENT; - fileSequenceProgressBar.opacity = fileSequenceProgressBar.opacity + OPACITY_INCREMENT; + if (fileSequenceProgressBar.animatedValue >= 100) { + fileSequenceProgressBar.animatedValue = 100 - } + fileSequenceProgressBar.opacity = fileSequenceProgressBar.opacity - OPACITY_INCREMENT + if (fileSequenceProgressBar.opacity < OPACITY_MIN) { fileSequenceProgressBar.opacity = OPACITY_MIN } - if (fileSequenceProgressBar.animatedValue >= 100) { + fileSequenceProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', fileSequenceProgressBar.opacity.toString()) + fileSequenceProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', fileSequenceProgressBar.opacity.toString()) - fileSequenceProgressBar.animatedValue = 100; + changeStatusTo(PRODUCT_CARD_STATUS.ON) + } - fileSequenceProgressBar.opacity = fileSequenceProgressBar.opacity - OPACITY_INCREMENT; - if (fileSequenceProgressBar.opacity < OPACITY_MIN) { fileSequenceProgressBar.opacity = OPACITY_MIN; } + point1 = { + x: 0, + y: thisObject.container.frame.height - 10 + } - fileSequenceProgressBar.fillStyle = LOADED_FILL_STYLE.replace('@Opacity', fileSequenceProgressBar.opacity.toString()); - fileSequenceProgressBar.strokeStyle = LOADED_STROKE_STYLE.replace('@Opacity', fileSequenceProgressBar.opacity.toString()); + point2 = { + x: thisObject.container.frame.width * fileSequenceProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 10 + } - changeStatusTo(PRODUCT_CARD_STATUS.ON); - } + point3 = { + x: thisObject.container.frame.width * fileSequenceProgressBar.animatedValue / 100, + y: thisObject.container.frame.height - 11 + } - point1 = { - x: 0, - y: thisObject.container.frame.height - 10 - }; - - point2 = { - x: thisObject.container.frame.width * fileSequenceProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 10 - }; - - point3 = { - x: thisObject.container.frame.width * fileSequenceProgressBar.animatedValue / 100, - y: thisObject.container.frame.height - 11 - }; - - point4 = { - x: 0, - y: thisObject.container.frame.height - 11 - }; + point4 = { + x: 0, + y: thisObject.container.frame.height - 11 + } /* Now the transformations. */ - point1 = thisObject.container.frame.frameThisPoint(point1); - point2 = thisObject.container.frame.frameThisPoint(point2); - point3 = thisObject.container.frame.frameThisPoint(point3); - point4 = thisObject.container.frame.frameThisPoint(point4); + point1 = thisObject.container.frame.frameThisPoint(point1) + point2 = thisObject.container.frame.frameThisPoint(point2) + point3 = thisObject.container.frame.frameThisPoint(point3) + point4 = thisObject.container.frame.frameThisPoint(point4) - browserCanvasContext.beginPath(); - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - browserCanvasContext.lineTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - browserCanvasContext.closePath(); + browserCanvasContext.beginPath() + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + browserCanvasContext.lineTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + browserCanvasContext.closePath() - browserCanvasContext.fillStyle = fileSequenceProgressBar.fillStyle.replace('@Opacity', fileSequenceProgressBar.opacity.toString()); - browserCanvasContext.strokeStyle = fileSequenceProgressBar.strokeStyle.replace('@Opacity', fileSequenceProgressBar.opacity.toString()); + browserCanvasContext.fillStyle = fileSequenceProgressBar.fillStyle.replace('@Opacity', fileSequenceProgressBar.opacity.toString()) + browserCanvasContext.strokeStyle = fileSequenceProgressBar.strokeStyle.replace('@Opacity', fileSequenceProgressBar.opacity.toString()) - browserCanvasContext.fill(); - browserCanvasContext.lineWidth = 0.1; - browserCanvasContext.stroke(); - } -} \ No newline at end of file + browserCanvasContext.fill() + browserCanvasContext.lineWidth = 0.1 + browserCanvasContext.stroke() + } + } diff --git a/ProductStorage.js b/ProductStorage.js index 5986ff494..9dffa6d5c 100644 --- a/ProductStorage.js +++ b/ProductStorage.js @@ -1,18 +1,17 @@ - -function newProductStorage(pName) { - - const MODULE_NAME = "Product Storage"; - const INFO_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; +  +function newProductStorage (pName) { + const MODULE_NAME = 'Product Storage' + const INFO_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME /* This object will initialize children objects that will end up loading the data of each set defined at each product of the bot received at initialization. Once all the underlaying objects are fully initialized it will callback. - At the same time it will raise an event for each underlaying file being loaded, so that the UI can reflect the progress to the end user. + At the same time it will raise an event for each underlaying file being loaded, so that the UI can reflect the progress to the end user. Product Storage | @@ -26,471 +25,403 @@ function newProductStorage(pName) { */ - let thisObject = { + let thisObject = { - marketFiles: [], - dailyFiles: [], - singleFile: [], - fileSequences: [], + marketFiles: [], + dailyFiles: [], + singleFile: [], + fileSequences: [], - setDatetime: setDatetime, - setTimePeriod: setTimePeriod, + setDatetime: setDatetime, + setTimePeriod: setTimePeriod, - eventHandler: undefined, - initialize: initialize, - finalize: finalize + eventHandler: undefined, + initialize: initialize, + finalize: finalize - } + } - thisObject.eventHandler = newEventHandler(); + thisObject.eventHandler = newEventHandler() /* We name the event Handler to easy debugging. */ - thisObject.eventHandler.name = "Storage-" + pName; + thisObject.eventHandler.name = 'Storage-' + pName - let datetime; - let timePeriod; + let datetime + let timePeriod - return thisObject; + return thisObject - function finalize() { + function finalize () { + try { + if (INFO_LOG === true) { logger.write('[INFO] finalize -> Entering function.') } - try { + for (let i = 0; i < thisObject.marketFiles.length; i++) { + let marketFile = thisObject.marketFiles[i] + marketFile.finalize() + } - if (INFO_LOG === true) { logger.write("[INFO] finalize -> Entering function."); } + thisObject.marketFiles = undefined - for (let i = 0; i < thisObject.marketFiles.length; i++) { + for (let i = 0; i < thisObject.dailyFiles.length; i++) { + let dailyFile = thisObject.dailyFiles[i] + dailyFile.finalize() + } - let marketFile = thisObject.marketFiles[i]; - marketFile.finalize(); - } + thisObject.dailyFile = undefined - thisObject.marketFiles = undefined; + for (let i = 0; i < thisObject.fileSequences.length; i++) { + let fileSequence = thisObject.fileSequences[i] + fileSequence.finalize() + } - for (let i = 0; i < thisObject.dailyFiles.length; i++) { - - let dailyFile = thisObject.dailyFiles[i]; - dailyFile.finalize(); - } - - thisObject.dailyFile = undefined; - - for (let i = 0; i < thisObject.fileSequences.length; i++) { - - let fileSequence = thisObject.fileSequences[i]; - fileSequence.finalize(); - } - - thisObject.dailyFile = undefined; - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] finalize -> err = " + err); } - } + thisObject.dailyFile = undefined + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] finalize -> err = ' + err) } } - - function initialize(pDevTeam, pBot, pProduct, pExchange, pMarket, pDatetime, pTimePeriod, callBackFunction) { + } - try { + function initialize (pDevTeam, pBot, pProduct, pExchange, pMarket, pDatetime, pTimePeriod, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } + datetime = pDatetime + timePeriod = pTimePeriod - datetime = pDatetime; - timePeriod = pTimePeriod; + let dataSetsToLoad = 0 + let dataSetsLoaded = 0 - let dataSetsToLoad = 0; - let dataSetsLoaded = 0; + if (INFO_LOG === true) { logger.write('[INFO] initialize -> dataSetsToLoad = ' + dataSetsToLoad) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> dataSetsLoaded = ' + dataSetsLoaded) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> dataSetsToLoad = " + dataSetsToLoad); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> dataSetsLoaded = " + dataSetsLoaded); } + for (let i = 0; i < pProduct.dataSets.length; i++) { + let thisSet = pProduct.dataSets[i] + switch (thisSet.type) { + case 'Market Files': { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Market Files -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - for (let i = 0; i < pProduct.dataSets.length; i++) { + dataSetsToLoad++ - let thisSet = pProduct.dataSets[i]; + if (INFO_LOG === true) { logger.write('[INFO] initialize -> dataSetsToLoad = ' + dataSetsToLoad) } - switch (thisSet.type) { - case 'Market Files': { + let marketFiles = newMarketFiles() + marketFiles.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, onMarketFileReady) + thisObject.marketFiles.push(marketFiles) + } + break - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Market Files -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } + case 'Daily Files': { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Daily Files -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - dataSetsToLoad++; + dataSetsToLoad++ - if (INFO_LOG === true) { logger.write("[INFO] initialize -> dataSetsToLoad = " + dataSetsToLoad); } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> dataSetsToLoad = ' + dataSetsToLoad) } - let marketFiles = newMarketFiles(); - marketFiles.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, onMarketFileReady); - thisObject.marketFiles.push(marketFiles); - } - break; + let dailyFiles = newDailyFiles() + dailyFiles.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, pDatetime, pTimePeriod, onDailyFileReady) + thisObject.dailyFiles.push(dailyFiles) + } + break - case 'Daily Files': { + case 'Single File': { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Single File -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Daily Files -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } + dataSetsToLoad++ - dataSetsToLoad++; + if (INFO_LOG === true) { logger.write('[INFO] initialize -> dataSetsToLoad = ' + dataSetsToLoad) } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> dataSetsToLoad = " + dataSetsToLoad); } + let singleFile = newSingleFile() + singleFile.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, onSingleFileReady) + thisObject.singleFile.push(singleFile) + } + break - let dailyFiles = newDailyFiles(); - dailyFiles.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, pDatetime, pTimePeriod, onDailyFileReady); - thisObject.dailyFiles.push(dailyFiles); - } - break; + case 'File Sequence': { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> File Sequence -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - case 'Single File': { + dataSetsToLoad++ - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Single File -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> dataSetsToLoad = ' + dataSetsToLoad) } - dataSetsToLoad++; + let fileSequences = newFileSequence() + fileSequences.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, onFileSequenceReady) + thisObject.fileSequences.push(fileSequences) + } + break + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> dataSetsToLoad = " + dataSetsToLoad); } + function onMarketFileReady (err, pCaller) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } - let singleFile = newSingleFile(); - singleFile.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, onSingleFileReady); - thisObject.singleFile.push(singleFile); - } - break; + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> Received OK Response.') } + break + } - case 'File Sequence': { + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> File Sequence -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> err.message = ' + err.message) } - dataSetsToLoad++; + callBackFunction(err) + return + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> dataSetsToLoad = " + dataSetsToLoad); } - - let fileSequences = newFileSequence(); - fileSequences.initialize(pDevTeam, pBot, pProduct, thisSet, pExchange, pMarket, onFileSequenceReady); - thisObject.fileSequences.push(fileSequences); - } - break; - } - - function onMarketFileReady(err, pCaller) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - let event = { - totalValue: pCaller.getExpectedFiles(), - currentValue: pCaller.getFilesLoaded() - } - - thisObject.eventHandler.raiseEvent('Market File Loaded', event); - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> event.currentValue = " + event.currentValue); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> event.totalValue = " + event.totalValue); } - - if (event.currentValue === event.totalValue) { - - dataSetsLoaded++; - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onMarketFileReady -> dataSetsLoaded = " + dataSetsLoaded); } - - checkInitializeComplete(); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onMarketFileReady -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function onDailyFileReady(err, pCaller) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - let event = { - totalValue: pCaller.getExpectedFiles(), - currentValue: pCaller.getFilesLoaded() - } - - thisObject.eventHandler.raiseEvent('Daily File Loaded', event); - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> event.currentValue = " + event.currentValue); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> event.totalValue = " + event.totalValue); } - - if (event.currentValue === event.totalValue) { - - dataSetsLoaded++; - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDailyFileReady -> dataSetsLoaded = " + dataSetsLoaded); } - - checkInitializeComplete(); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onDailyFileReady -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function onSingleFileReady(err, pCaller) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - let event = { - totalValue: 1, - currentValue: 1 - } - - thisObject.eventHandler.raiseEvent('Single File Loaded', event); - - if (event.currentValue === event.totalValue) { - - dataSetsLoaded++; - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onSingleFileReady -> dataSetsLoaded = " + dataSetsLoaded); } - - checkInitializeComplete(); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onSingleFileReady -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function onFileSequenceReady(err, pCaller) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - switch (err.result) { - case GLOBAL.DEFAULT_OK_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received OK Response."); } - break; - } - - case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received FAIL Response."); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } - - case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received CUSTOM FAIL Response."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> err.message = " + err.message); } - - callBackFunction(err); - return; - } - - default: { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady -> Received Unexpected Response."); } - callBackFunction(err); - return; - } - } - - let event = { - totalValue: pCaller.getExpectedFiles(), - currentValue: pCaller.getFilesLoaded() - } - - thisObject.eventHandler.raiseEvent('File Sequence Loaded', event); - - if (event.currentValue === event.totalValue) { - - dataSetsLoaded++; - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onFileSequenceReady = " + dataSetsLoaded); } - - checkInitializeComplete(); - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onFileSequenceReady -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function checkInitializeComplete() { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> checkInitializeComplete -> Entering function."); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> checkInitializeComplete -> key = " + pDevTeam.codeName + "-" + pBot.codeName + "-" + pProduct.codeName); } - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> checkInitializeComplete -> dataSetsToLoad = " + dataSetsToLoad); } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> checkInitializeComplete -> dataSetsLoaded = " + dataSetsLoaded); } - - if (dataSetsLoaded === dataSetsToLoad) { - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> checkInitializeComplete -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> Received Unexpected Response.') } + callBackFunction(err) + return + } } - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); + let event = { + totalValue: pCaller.getExpectedFiles(), + currentValue: pCaller.getFilesLoaded() + } + + thisObject.eventHandler.raiseEvent('Market File Loaded', event) + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> event.currentValue = ' + event.currentValue) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> event.totalValue = ' + event.totalValue) } + + if (event.currentValue === event.totalValue) { + dataSetsLoaded++ + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> dataSetsLoaded = ' + dataSetsLoaded) } + + checkInitializeComplete() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onMarketFileReady -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } } + + function onDailyFileReady (err, pCaller) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } + + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> Received OK Response.') } + break + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> err.message = ' + err.message) } + + callBackFunction(err) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + let event = { + totalValue: pCaller.getExpectedFiles(), + currentValue: pCaller.getFilesLoaded() + } + + thisObject.eventHandler.raiseEvent('Daily File Loaded', event) + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> event.currentValue = ' + event.currentValue) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> event.totalValue = ' + event.totalValue) } + + if (event.currentValue === event.totalValue) { + dataSetsLoaded++ + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDailyFileReady -> dataSetsLoaded = ' + dataSetsLoaded) } + + checkInitializeComplete() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onDailyFileReady -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + + function onSingleFileReady (err, pCaller) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } + + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> Received OK Response.') } + break + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> err.message = ' + err.message) } + + callBackFunction(err) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + let event = { + totalValue: 1, + currentValue: 1 + } + + thisObject.eventHandler.raiseEvent('Single File Loaded', event) + + if (event.currentValue === event.totalValue) { + dataSetsLoaded++ + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onSingleFileReady -> dataSetsLoaded = ' + dataSetsLoaded) } + + checkInitializeComplete() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onSingleFileReady -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + + function onFileSequenceReady (err, pCaller) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } + + switch (err.result) { + case GLOBAL.DEFAULT_OK_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received OK Response.') } + break + } + + case GLOBAL.DEFAULT_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received FAIL Response.') } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } + + case GLOBAL.CUSTOM_FAIL_RESPONSE.result: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received CUSTOM FAIL Response.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> err.message = ' + err.message) } + + callBackFunction(err) + return + } + + default: { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady -> Received Unexpected Response.') } + callBackFunction(err) + return + } + } + + let event = { + totalValue: pCaller.getExpectedFiles(), + currentValue: pCaller.getFilesLoaded() + } + + thisObject.eventHandler.raiseEvent('File Sequence Loaded', event) + + if (event.currentValue === event.totalValue) { + dataSetsLoaded++ + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onFileSequenceReady = ' + dataSetsLoaded) } + + checkInitializeComplete() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onFileSequenceReady -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + + function checkInitializeComplete () { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> checkInitializeComplete -> Entering function.') } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> checkInitializeComplete -> key = ' + pDevTeam.codeName + '-' + pBot.codeName + '-' + pProduct.codeName) } + + if (INFO_LOG === true) { logger.write('[INFO] initialize -> checkInitializeComplete -> dataSetsToLoad = ' + dataSetsToLoad) } + if (INFO_LOG === true) { logger.write('[INFO] initialize -> checkInitializeComplete -> dataSetsLoaded = ' + dataSetsLoaded) } + + if (dataSetsLoaded === dataSetsToLoad) { + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> checkInitializeComplete -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) } + } - function setDatetime(pDatetime) { - - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> Entering function."); } + function setDatetime (pDatetime) { + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> Entering function.') } /* If there is a change in the day, then we take some actions, otherwise, we dont. */ - let currentDate = Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS); - let newDate = Math.trunc(pDatetime.valueOf() / ONE_DAY_IN_MILISECONDS); + let currentDate = Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS) + let newDate = Math.trunc(pDatetime.valueOf() / ONE_DAY_IN_MILISECONDS) - datetime = new Date(pDatetime); + datetime = new Date(pDatetime) - if (currentDate !== newDate) { - - if (timePeriod <= _1_HOUR_IN_MILISECONDS) { - - for (let i = 0; i < thisObject.dailyFiles.length; i++) { - - thisObject.dailyFiles[i].setDatetime(pDatetime); - } - } + if (currentDate !== newDate) { + if (timePeriod <= _1_HOUR_IN_MILISECONDS) { + for (let i = 0; i < thisObject.dailyFiles.length; i++) { + thisObject.dailyFiles[i].setDatetime(pDatetime) } - + } } + } - function setTimePeriod(pTimePeriod) { - - if (INFO_LOG === true) { logger.write("[INFO] setTimePeriod -> Entering function."); } + function setTimePeriod (pTimePeriod) { + if (INFO_LOG === true) { logger.write('[INFO] setTimePeriod -> Entering function.') } /* We are going to filter out the cases in which the timePeriod received is the same that the one we already know. */ - if (timePeriod !== pTimePeriod) { + if (timePeriod !== pTimePeriod) { + timePeriod = pTimePeriod - timePeriod = pTimePeriod; - - if (timePeriod <= _1_HOUR_IN_MILISECONDS) { - - for (let i = 0; i < thisObject.dailyFiles.length; i++) { - - thisObject.dailyFiles[i].setTimePeriod(pTimePeriod, datetime); - } - } + if (timePeriod <= _1_HOUR_IN_MILISECONDS) { + for (let i = 0; i < thisObject.dailyFiles.length; i++) { + thisObject.dailyFiles[i].setTimePeriod(pTimePeriod, datetime) } + } } + } } diff --git a/Scales/ChartGrid.js b/Scales/ChartGrid.js index 2f0323659..d548d0d1a 100644 --- a/Scales/ChartGrid.js +++ b/Scales/ChartGrid.js @@ -1,769 +1,712 @@ -function newChartGrid() { + function newChartGrid () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 0 + thisObject.container.frame.height = 0 - thisObject.container.frame.width = 0; - thisObject.container.frame.height = 0; + container.frame.position.x = 0 + container.frame.position.y = 0 - container.frame.position.x = 0; - container.frame.position.y = 0; + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + let rigthScale - let rigthScale; + return thisObject - return thisObject; + function initialize () { + rigthScale = newRigthScale() + rigthScale.initialize() + } - function initialize() { + function getContainer (point) { + let container - rigthScale = newRigthScale(); - rigthScale.initialize(); + container = rigthScale.getContainer(point) - } - - function getContainer(point) { - - let container; - - container = rigthScale.getContainer(point); - - if (container !== undefined) { - - return container; - - } - - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { + if (container !== undefined) { + return container + } + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } + return undefined + } + } - } + function draw (container, timeLineCoordinateSystem) { + rightScaleBackground() + leftScaleBackground() - function draw(container, timeLineCoordinateSystem) { + let periods = [] + let boxes = [] + let labels = [] - rightScaleBackground(); - leftScaleBackground(); + const basePeriod = { + x: 8 * 60 * 60 * 1000, + y: timeLineCoordinateSystem.max.y / 1000 / canvas.bottomSpace.chartAspectRatio.aspectRatio.y + } - let periods = []; - let boxes = []; - let labels = []; + let period = { + x: basePeriod.x, + y: basePeriod.y + } - const basePeriod = { - x: 8 * 60 * 60 * 1000, - y: timeLineCoordinateSystem.max.y / 1000 / canvas.bottomSpace.chartAspectRatio.aspectRatio.y - }; + calculateTimeLabels() + printLabels(1000, 10000) - let period = { - x: basePeriod.x, - y: basePeriod.y - }; + function calculateTimeLabels () { + periods.push(period) // 0 - calculateTimeLabels(); - printLabels(1000, 10000); + period = { + x: basePeriod.x / 8, + y: basePeriod.y / 10 + } - function calculateTimeLabels() { + periods.push(period) // 1 - periods.push(period); // 0 + period = { + x: basePeriod.x / 8 / 6, + y: basePeriod.y / 100 + } - period = { - x: basePeriod.x / 8, - y: basePeriod.y / 10 - }; + periods.push(period) // 2 - periods.push(period); // 1 + period = { + x: basePeriod.x * 3, + y: basePeriod.y * 10 + } - period = { - x: basePeriod.x / 8 / 6, - y: basePeriod.y / 100 - }; + periods.push(period) // 3 - periods.push(period); // 2 + period = { + x: basePeriod.x * 3 * 7, + y: basePeriod.y * 100 + } - period = { - x: basePeriod.x * 3, - y: basePeriod.y * 10 - }; - - periods.push(period); // 3 - - period = { - x: basePeriod.x * 3 * 7, - y: basePeriod.y * 100 - }; - - periods.push(period); // 4 + periods.push(period) // 4 /* Period #2 Plotting */ - boxes = []; - plotGrid(periods[2]); - labels = []; + boxes = [] + plotGrid(periods[2]) + labels = [] /* Label Calculation */ - for (let i = 0; i < boxes.length; i++) { + for (let i = 0; i < boxes.length; i++) { + const UPPER_PERIOD = 1 - const UPPER_PERIOD = 1; + let box = boxes[i] + let currentValue = box.topLeft - let box = boxes[i]; - let currentValue = box.topLeft; - - currentValue = unTransformThisPoint(currentValue, container); - currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height); + currentValue = unTransformThisPoint(currentValue, container) + currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height) /* We must compare the current value on the current period, against the next period, to know which cell we are in. */ - let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000); + let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000) - switch (distanceToNextPeriod) { - case 0: { - labels.push("0"); - break; - } - case Math.trunc(1 / 6 * 1000): { + switch (distanceToNextPeriod) { + case 0: { + labels.push('0') + break + } + case Math.trunc(1 / 6 * 1000): { - } - labels.push("10"); - break; - case Math.trunc(2 / 6 * 1000): { + } + labels.push('10') + break + case Math.trunc(2 / 6 * 1000): { - } - labels.push("20"); - break; + } + labels.push('20') + break - case Math.trunc(3 / 6 * 1000): { + case Math.trunc(3 / 6 * 1000): { - } - labels.push("30"); - break; + } + labels.push('30') + break - case Math.trunc(4 / 6 * 1000): { + case Math.trunc(4 / 6 * 1000): { - } - labels.push("40"); - break; + } + labels.push('40') + break - case Math.trunc(5 / 6 * 1000): { + case Math.trunc(5 / 6 * 1000): { - } - labels.push("50"); - break; + } + labels.push('50') + break - } + } + } - } - - printLabels(1, 150); + printLabels(1, 150) /* Period #1 Plotting */ - boxes = []; - plotGrid(periods[1]); - labels = []; + boxes = [] + plotGrid(periods[1]) + labels = [] /* Label Calculation */ - for (let i = 0; i < boxes.length; i++) { + for (let i = 0; i < boxes.length; i++) { + const UPPER_PERIOD = 3 - const UPPER_PERIOD = 3; + let box = boxes[i] + let currentValue = box.topLeft - let box = boxes[i]; - let currentValue = box.topLeft; - - currentValue = unTransformThisPoint(currentValue, container); - currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height); + currentValue = unTransformThisPoint(currentValue, container) + currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height) /* We must compare the current value on the current period, against the next period, to know which cell we are in. */ - let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000); + let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000) - switch (distanceToNextPeriod) { - case 0: { - labels.push("0 Hs"); - break; - } - case Math.trunc(1 / 24 * 1000): { + switch (distanceToNextPeriod) { + case 0: { + labels.push('0 Hs') + break + } + case Math.trunc(1 / 24 * 1000): { - } - labels.push("1 Hs"); - break; - case Math.trunc(2 / 24 * 1000): { + } + labels.push('1 Hs') + break + case Math.trunc(2 / 24 * 1000): { - } - labels.push("2 Hs"); - break; + } + labels.push('2 Hs') + break - case Math.trunc(3 / 24 * 1000): { + case Math.trunc(3 / 24 * 1000): { - } - labels.push("3 Hs"); - break; + } + labels.push('3 Hs') + break - case Math.trunc(4 / 24 * 1000): { + case Math.trunc(4 / 24 * 1000): { - } - labels.push("4 Hs"); - break; + } + labels.push('4 Hs') + break - case Math.trunc(5 / 24 * 1000): { + case Math.trunc(5 / 24 * 1000): { - } - labels.push("5 Hs"); - break; + } + labels.push('5 Hs') + break - case Math.trunc(6 / 24 * 1000): { + case Math.trunc(6 / 24 * 1000): { - } - labels.push("6 Hs"); - break; + } + labels.push('6 Hs') + break - case Math.trunc(7 / 24 * 1000): { + case Math.trunc(7 / 24 * 1000): { - } - labels.push("7 Hs"); - break; + } + labels.push('7 Hs') + break - case Math.trunc(8 / 24 * 1000): { + case Math.trunc(8 / 24 * 1000): { - } - labels.push("8 Hs"); - break; + } + labels.push('8 Hs') + break - case Math.trunc(9 / 24 * 1000): { + case Math.trunc(9 / 24 * 1000): { - } - labels.push("9 Hs"); - break; + } + labels.push('9 Hs') + break - case Math.trunc(10 / 24 * 1000): { + case Math.trunc(10 / 24 * 1000): { - } - labels.push("10 Hs"); - break; + } + labels.push('10 Hs') + break - case Math.trunc(11 / 24 * 1000): { + case Math.trunc(11 / 24 * 1000): { - } - labels.push("11 Hs"); - break; + } + labels.push('11 Hs') + break - case Math.trunc(12 / 24 * 1000): { + case Math.trunc(12 / 24 * 1000): { - } - labels.push("12 Hs"); - break; + } + labels.push('12 Hs') + break - case Math.trunc(13 / 24 * 1000): { + case Math.trunc(13 / 24 * 1000): { - } - labels.push("13 Hs"); - break; + } + labels.push('13 Hs') + break - case Math.trunc(14 / 24 * 1000): { + case Math.trunc(14 / 24 * 1000): { - } - labels.push("14 Hs"); - break; + } + labels.push('14 Hs') + break - case Math.trunc(15 / 24 * 1000): { + case Math.trunc(15 / 24 * 1000): { - } - labels.push("15 Hs"); - break; + } + labels.push('15 Hs') + break - case Math.trunc(16 / 24 * 1000): { + case Math.trunc(16 / 24 * 1000): { - } - labels.push("16 Hs"); - break; + } + labels.push('16 Hs') + break - case Math.trunc(17 / 24 * 1000): { + case Math.trunc(17 / 24 * 1000): { - } - labels.push("17 Hs"); - break; + } + labels.push('17 Hs') + break - case Math.trunc(18 / 24 * 1000): { + case Math.trunc(18 / 24 * 1000): { - } - labels.push("18 Hs"); - break; + } + labels.push('18 Hs') + break - case Math.trunc(19 / 24 * 1000): { + case Math.trunc(19 / 24 * 1000): { - } - labels.push("19 Hs"); - break; + } + labels.push('19 Hs') + break - case Math.trunc(20 / 24 * 1000): { + case Math.trunc(20 / 24 * 1000): { - } - labels.push("20 Hs"); - break; + } + labels.push('20 Hs') + break - case Math.trunc(21 / 24 * 1000): { + case Math.trunc(21 / 24 * 1000): { - } - labels.push("21 Hs"); - break; + } + labels.push('21 Hs') + break - case Math.trunc(22 / 24 * 1000): { + case Math.trunc(22 / 24 * 1000): { - } - labels.push("22 Hs"); - break; + } + labels.push('22 Hs') + break - case Math.trunc(23 / 24 * 1000): { + case Math.trunc(23 / 24 * 1000): { - } - labels.push("23 Hs"); - break; - } + } + labels.push('23 Hs') + break + } + } - } - - printLabels(5, 250); + printLabels(5, 250) /* Period #0 Plotting */ - boxes = []; - plotGrid(periods[0]); - labels = []; + boxes = [] + plotGrid(periods[0]) + labels = [] /* Label Calculation */ - for (let i = 0; i < boxes.length; i++) { + for (let i = 0; i < boxes.length; i++) { + const UPPER_PERIOD = 3 - const UPPER_PERIOD = 3; + let box = boxes[i] + let currentValue = box.topLeft - let box = boxes[i]; - let currentValue = box.topLeft; - - currentValue = unTransformThisPoint(currentValue, container); - currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height); + currentValue = unTransformThisPoint(currentValue, container) + currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height) /* We must compare the current value on the current period, against the next period, to know which cell we are in. */ - let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000); + let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000) - switch (distanceToNextPeriod) { - case 0: { - labels.push("Morning"); - break; - } - case Math.trunc(1 / 3 * 1000): { + switch (distanceToNextPeriod) { + case 0: { + labels.push('Morning') + break + } + case Math.trunc(1 / 3 * 1000): { - } - labels.push("Afternoon"); - break; - case Math.trunc(2 / 3 * 1000): { + } + labels.push('Afternoon') + break + case Math.trunc(2 / 3 * 1000): { - } - labels.push("Evening"); - break; - } + } + labels.push('Evening') + break + } + } - } - - printLabels(15, 50); + printLabels(15, 50) /* Period #3 Plotting */ - boxes = []; - plotGrid(periods[3]); - labels = []; + boxes = [] + plotGrid(periods[3]) + labels = [] /* Label Calculation */ - for (let i = 0; i < boxes.length; i++) { + for (let i = 0; i < boxes.length; i++) { + const UPPER_PERIOD = 1 - const UPPER_PERIOD = 1; + let box = boxes[i] + let currentValue = box.topLeft - let box = boxes[i]; - let currentValue = box.topLeft; + currentValue = unTransformThisPoint(currentValue, container) + currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height) - currentValue = unTransformThisPoint(currentValue, container); - currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height); + let date = new Date(currentValue.x) - let date = new Date(currentValue.x); + labels.push(date.toDateString()) + } - labels.push(date.toDateString()); - - } - - printLabels(100, 2250); + printLabels(100, 2250) /* Period #4 Plotting */ - boxes = []; - plotGrid(periods[4]); - labels = []; + boxes = [] + plotGrid(periods[4]) + labels = [] /* Label Calculation */ - for (let i = 0; i < boxes.length; i++) { + for (let i = 0; i < boxes.length; i++) { + const UPPER_PERIOD = 1 - const UPPER_PERIOD = 1; + let box = boxes[i] + let currentValue = box.topLeft - let box = boxes[i]; - let currentValue = box.topLeft; + currentValue = unTransformThisPoint(currentValue, container) + currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height) - currentValue = unTransformThisPoint(currentValue, container); - currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height); + let date = new Date(currentValue.x) - let date = new Date(currentValue.x); + var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + labels.push(monthNames[date.getMonth()] + ' ' + date.getFullYear()) + } + } - labels.push(monthNames[date.getMonth()] + ' ' + date.getFullYear()); + function plotGrid (period) { + let periodWidth = period.x + let periodHeight = period.y - } + let visiblePoint1 = { + x: viewPort.visibleArea.topLeft.x, + y: viewPort.visibleArea.bottomLeft.y + } - } + visiblePoint1 = unTransformThisPoint(visiblePoint1, container) + visiblePoint1 = timeLineCoordinateSystem.unInverseTransform(visiblePoint1, container.frame.height) - function plotGrid(period) { + let visiblePoint2 = { + x: viewPort.visibleArea.bottomRight.x, + y: viewPort.visibleArea.topRight.y + } + visiblePoint2 = unTransformThisPoint(visiblePoint2, container) + visiblePoint2 = timeLineCoordinateSystem.unInverseTransform(visiblePoint2, container.frame.height) - let periodWidth = period.x; - let periodHeight = period.y; + startingPoint = { + x: Math.trunc(visiblePoint1.x / periodWidth) * periodWidth, + y: Math.round(Math.trunc(visiblePoint1.y / periodHeight) * periodHeight * 100000) / 100000 + } - let visiblePoint1 = { - x: viewPort.visibleArea.topLeft.x, - y: viewPort.visibleArea.bottomLeft.y - }; + endingPoint = { + x: Math.trunc(visiblePoint2.x / periodWidth) * periodWidth, + y: Math.trunc(visiblePoint2.y / periodHeight) * periodHeight + } - visiblePoint1 = unTransformThisPoint(visiblePoint1, container); - visiblePoint1 = timeLineCoordinateSystem.unInverseTransform(visiblePoint1, container.frame.height); + let lineWidth - let visiblePoint2 = { - x: viewPort.visibleArea.bottomRight.x, - y: viewPort.visibleArea.topRight.y - }; + if (viewPort.zoomLevel > 0) { + lineWidth = period.x / basePeriod.x + period.x / basePeriod.x * viewPort.zoomLevel / 20 + } else { + lineWidth = period.x / basePeriod.x + period.x / basePeriod.x * viewPort.zoomLevel / 80 + } - visiblePoint2 = unTransformThisPoint(visiblePoint2, container); - visiblePoint2 = timeLineCoordinateSystem.unInverseTransform(visiblePoint2, container.frame.height); + if (lineWidth < 0.7) { + return + } - startingPoint = { - x: Math.trunc(visiblePoint1.x / periodWidth) * periodWidth, - y: Math.round(Math.trunc(visiblePoint1.y / periodHeight) * periodHeight * 100000) / 100000 - }; + if (lineWidth > 1.4) { + lineWidth = 1.4 + } - endingPoint = { - x: Math.trunc(visiblePoint2.x / periodWidth) * periodWidth, - y: Math.trunc(visiblePoint2.y / periodHeight) * periodHeight - }; + browserCanvasContext.beginPath() - let lineWidth; + let y1 + let y2 - if (viewPort.zoomLevel > 0) { + let lastRightLabelPosition = { + x: 0, + y: 0 + } - lineWidth = period.x / basePeriod.x + period.x / basePeriod.x * viewPort.zoomLevel / 20; + let lastLeftLabelPosition = { + x: 0, + y: 0 + } - } else { + for (var j = startingPoint.y; j <= endingPoint.y + periodHeight; j = j + periodHeight) { + if (j >= 0 && j <= timeLineCoordinateSystem.max.y) { + let point1 = { + x: visiblePoint1.x, + y: j + } - lineWidth = period.x / basePeriod.x + period.x / basePeriod.x * viewPort.zoomLevel / 80; + let point2 = { + x: visiblePoint2.x, + y: j + } - } + point1 = timeLineCoordinateSystem.transformThisPoint(point1) + point2 = timeLineCoordinateSystem.transformThisPoint(point2) + point1 = transformThisPoint(point1, container) + point2 = transformThisPoint(point2, container) - if (lineWidth < 0.7) { - return; - } - - if (lineWidth > 1.4) { - lineWidth = 1.4; - } - - browserCanvasContext.beginPath(); - - let y1; - let y2; - - let lastRightLabelPosition = { - x: 0, - y: 0 - }; - - let lastLeftLabelPosition = { - x: 0, - y: 0 - }; - - for (var j = startingPoint.y; j <= endingPoint.y + periodHeight; j = j + periodHeight) { - - if (j >= 0 && j <= timeLineCoordinateSystem.max.y) { - - let point1 = { - x: visiblePoint1.x, - y: j - }; - - let point2 = { - x: visiblePoint2.x, - y: j - }; - - point1 = timeLineCoordinateSystem.transformThisPoint(point1); - point2 = timeLineCoordinateSystem.transformThisPoint(point2); - - point1 = transformThisPoint(point1, container); - point2 = transformThisPoint(point2, container); - - if (point1.y >= viewPort.visibleArea.topLeft.y) { - + if (point1.y >= viewPort.visibleArea.topLeft.y) { /* Here we keep the last two positive valued of y */ - y2 = y1; - y1 = point1.y; + y2 = y1 + y1 = point1.y + } - } + point1 = viewPort.fitIntoVisibleArea(point1) + point2 = viewPort.fitIntoVisibleArea(point2) - point1 = viewPort.fitIntoVisibleArea(point1); - point2 = viewPort.fitIntoVisibleArea(point2); - - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) /* Now we put the scale on the right side of the chart */ - drawRigthScale(); - drawLeftScale(); - - function drawRigthScale() { + drawRigthScale() + drawLeftScale() + function drawRigthScale () { /* And now the scale. */ - let fontSize = 10; + let fontSize = 10 - let label = ' ' + Math.round(j * 1) / 1; - label = Number(label).toLocaleString(); + let label = ' ' + Math.round(j * 1) / 1 + label = Number(label).toLocaleString() - let labelPoint = { - x: viewPort.visibleArea.bottomRight.x + 5, - y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO - }; + let labelPoint = { + x: viewPort.visibleArea.bottomRight.x + 5, + y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO + } - if (Math.abs(lastRightLabelPosition.y - labelPoint.y > fontSize || lastRightLabelPosition.y === 0)) { + if (Math.abs(lastRightLabelPosition.y - labelPoint.y > fontSize || lastRightLabelPosition.y === 0)) { + if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) { + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + } + } - if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) { + lastRightLabelPosition.x = labelPoint.x + lastRightLabelPosition.y = labelPoint.y + } - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + function drawLeftScale () { + let fontSize = 10 - } - } - - lastRightLabelPosition.x = labelPoint.x; - lastRightLabelPosition.y = labelPoint.y; - - } - - function drawLeftScale() { - - let fontSize = 10; - - /* + /* j is a value between 0 and the max y on the scale of the products. If we want to convert j to the scale of profits we need to apply the following formula: */ - let labelValue = (j - timeLineCoordinateSystem.max.y / 2) * 200 / timeLineCoordinateSystem.max.y; - labelValue = Math.round(labelValue * 100) / 100; - if (labelValue > 0) { labelValue = '+' + labelValue; } - if (parseInt(labelValue) > -10 && parseInt(labelValue) < 10) { labelValue = ' ' + labelValue; } - if (parseInt(labelValue) === 0) { labelValue = ' ' + labelValue; } - let label = ' ' + pad(labelValue, 3) + '%'; + let labelValue = (j - timeLineCoordinateSystem.max.y / 2) * 200 / timeLineCoordinateSystem.max.y + labelValue = Math.round(labelValue * 100) / 100 + if (labelValue > 0) { labelValue = '+' + labelValue } + if (parseInt(labelValue) > -10 && parseInt(labelValue) < 10) { labelValue = ' ' + labelValue } + if (parseInt(labelValue) === 0) { labelValue = ' ' + labelValue } + let label = ' ' + pad(labelValue, 3) + '%' - let labelPoint = { - x: 0, - y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO - }; + let labelPoint = { + x: 0, + y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO + } - if (Math.abs(lastLeftLabelPosition.y - labelPoint.y > fontSize || lastLeftLabelPosition.y === 0)) { + if (Math.abs(lastLeftLabelPosition.y - labelPoint.y > fontSize || lastLeftLabelPosition.y === 0)) { + if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) { + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + } + } - if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) { + lastLeftLabelPosition.x = labelPoint.x + lastLeftLabelPosition.y = labelPoint.y + } + } + } - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); + let x1 + let x2 - } - } + for (var i = startingPoint.x; i <= endingPoint.x + periodWidth; i = i + periodWidth) { + let point3 = { + x: i, + y: 0 + } - lastLeftLabelPosition.x = labelPoint.x; - lastLeftLabelPosition.y = labelPoint.y; + let point4 = { + x: i, + y: timeLineCoordinateSystem.max.y + } - } - } - } + point3 = timeLineCoordinateSystem.transformThisPoint(point3) + point4 = timeLineCoordinateSystem.transformThisPoint(point4) - let x1; - let x2; - - for (var i = startingPoint.x; i <= endingPoint.x + periodWidth; i = i + periodWidth) { - - let point3 = { - x: i, - y: 0 - }; - - let point4 = { - x: i, - y: timeLineCoordinateSystem.max.y - }; - - point3 = timeLineCoordinateSystem.transformThisPoint(point3); - point4 = timeLineCoordinateSystem.transformThisPoint(point4); - - point3 = transformThisPoint(point3, container); - point4 = transformThisPoint(point4, container); + point3 = transformThisPoint(point3, container) + point4 = transformThisPoint(point4, container) /* Here we keep the last two positive valued of y */ - x2 = x1; - x1 = point3.x; + x2 = x1 + x1 = point3.x - if (x2 !== undefined) { + if (x2 !== undefined) { + let topLeft = { + x: x2, + y: y1 + } - let topLeft = { - x: x2, - y: y1 - }; - - let bottomRight = { - x: x1, - y: y2 - }; - - let box = { - topLeft: topLeft, - bottomRight: bottomRight - }; - boxes.push(box); - } + let bottomRight = { + x: x1, + y: y2 + } + let box = { + topLeft: topLeft, + bottomRight: bottomRight + } + boxes.push(box) + } /* Painting the lines */ - point3 = viewPort.fitIntoVisibleArea(point3); - point4 = viewPort.fitIntoVisibleArea(point4); + point3 = viewPort.fitIntoVisibleArea(point3) + point4 = viewPort.fitIntoVisibleArea(point4) - browserCanvasContext.moveTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); + browserCanvasContext.moveTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + } + browserCanvasContext.closePath() + browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.' + Math.trunc(lineWidth + 1) + ')' + browserCanvasContext.lineWidth = lineWidth - } + browserCanvasContext.stroke() + } - browserCanvasContext.closePath(); - browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.' + Math.trunc(lineWidth + 1) + ')'; + function printLabels (baseZoomFilter, maxZoom) { + let zoomFilter = viewPort.zoomFontSize(baseZoomFilter) - browserCanvasContext.lineWidth = lineWidth; + if (zoomFilter < 7 || zoomFilter > maxZoom) { + return + } - browserCanvasContext.stroke(); + for (let i = 0; i < boxes.length; i++) { + let label = labels[i] - } + if (label === undefined) { + label = 'undefined' + } - function printLabels(baseZoomFilter, maxZoom) { + let fontSize = 10 - let zoomFilter = viewPort.zoomFontSize(baseZoomFilter); + let labelPoint = { + x: boxes[i].topLeft.x - label.length / 2 * fontSize * FONT_ASPECT_RATIO, + y: viewPort.visibleArea.topLeft.y - fontSize / 2 + 1 + } - if (zoomFilter < 7 || zoomFilter > maxZoom) { - return; - } + let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO - for (let i = 0; i < boxes.length; i++) { + browserCanvasContext.beginPath() - let label = labels[i]; + browserCanvasContext.rect(labelPoint.x, labelPoint.y - fontSize, xOffset * 2, fontSize) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fill() - if (label === undefined) { - label = "undefined"; - } + browserCanvasContext.closePath() - let fontSize = 10; + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) + } - let labelPoint = { - x: boxes[i].topLeft.x - label.length / 2 * fontSize * FONT_ASPECT_RATIO, - y: viewPort.visibleArea.topLeft.y - fontSize / 2 + 1 - }; + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.beginPath() + browserCanvasContext.rect(0, TOP_SPACE_HEIGHT, viewPort.visibleArea.topLeft.x, viewPort.visibleArea.topLeft.y - TOP_SPACE_HEIGHT) + browserCanvasContext.rect(viewPort.visibleArea.topRight.x, TOP_SPACE_HEIGHT, 500, viewPort.visibleArea.topLeft.y - TOP_SPACE_HEIGHT) + browserCanvasContext.closePath() + browserCanvasContext.fill() + } - let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO; - - browserCanvasContext.beginPath(); - - browserCanvasContext.rect(labelPoint.x, labelPoint.y - fontSize, xOffset * 2, fontSize ); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fill(); - - browserCanvasContext.closePath(); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); - } - - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.beginPath(); - browserCanvasContext.rect(0, TOP_SPACE_HEIGHT, viewPort.visibleArea.topLeft.x, viewPort.visibleArea.topLeft.y - TOP_SPACE_HEIGHT); - browserCanvasContext.rect(viewPort.visibleArea.topRight.x, TOP_SPACE_HEIGHT, 500, viewPort.visibleArea.topLeft.y - TOP_SPACE_HEIGHT); - browserCanvasContext.closePath(); - browserCanvasContext.fill(); - } - - function rightScaleBackground() { - - const RIGHT_MARGIN = 50; + function rightScaleBackground () { + const RIGHT_MARGIN = 50 /* We will paint some transparent background here. */ - let opacity = "0.95"; + let opacity = '0.95' - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - browserCanvasContext.rect(viewPort.visibleArea.topRight.x, viewPort.visibleArea.topRight.y, RIGHT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'; + browserCanvasContext.rect(viewPort.visibleArea.topRight.x, viewPort.visibleArea.topRight.y, RIGHT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')' - browserCanvasContext.closePath(); + browserCanvasContext.closePath() - browserCanvasContext.fill(); + browserCanvasContext.fill() + } - } - - function leftScaleBackground() { - - const LEFT_MARGIN = 50; + function leftScaleBackground () { + const LEFT_MARGIN = 50 /* We will paint some transparent background here. */ - let opacity = "0.95"; + let opacity = '0.95' - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - browserCanvasContext.rect(0, viewPort.visibleArea.topRight.y, LEFT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'; + browserCanvasContext.rect(0, viewPort.visibleArea.topRight.y, LEFT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')' - browserCanvasContext.closePath(); + browserCanvasContext.closePath() - browserCanvasContext.fill(); - - } - } -} + browserCanvasContext.fill() + } + } + } diff --git a/Scales/RightScale.js b/Scales/RightScale.js index 72e31101c..c37f63994 100644 --- a/Scales/RightScale.js +++ b/Scales/RightScale.js @@ -1,67 +1,56 @@ -function newRigthScale() { + function newRigthScale () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + const RIGHT_MARGIN = 50 - const RIGHT_MARGIN = 50; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = RIGHT_MARGIN + thisObject.container.frame.height = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y - thisObject.container.frame.width = RIGHT_MARGIN; - thisObject.container.frame.height = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y; + container.frame.position.x = viewPort.visibleArea.bottomRight.x + container.frame.position.y = TOP_SPACE_HEIGHT - container.frame.position.x = viewPort.visibleArea.bottomRight.x; - container.frame.position.y = TOP_SPACE_HEIGHT; + container.isDraggeable = false + container.isClickeable = false + container.isWheeleable = true - container.isDraggeable = false; - container.isClickeable = false; - container.isWheeleable = true; + return thisObject - return thisObject; + function initialize () { + thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel) + } - function initialize() { + function onMouseWheel (pDelta) { + if (pDelta < 0) { + pDelta = -0.1 + } else { + pDelta = 0.1 + } + } - thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel); - - } - - function onMouseWheel(pDelta) { - - if (pDelta < 0) { - pDelta = -0.1; - } else { - pDelta = 0.1; - } - - } - - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - } + return undefined + } + } - function draw() { + function draw () { - - } - -} \ No newline at end of file + } + } diff --git a/Spaces/BottomSpace.js b/Spaces/BottomSpace.js index e6bb3bf98..a778e39fd 100644 --- a/Spaces/BottomSpace.js +++ b/Spaces/BottomSpace.js @@ -1,105 +1,95 @@ - -function newBottomSpace() { +  +function newBottomSpace () { + var thisObject = { + deleteTradingHistory: undefined, + chartAspectRatio: undefined, + playStopButton: undefined, + container: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - deleteTradingHistory: undefined, - chartAspectRatio: undefined, - playStopButton: undefined, - container: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container - var container = newContainer(); - container.initialize(); - thisObject.container = container; + container.isDraggeable = false - container.isDraggeable = false; + resize() - resize(); + return thisObject - return thisObject; + function initialize () { + thisObject.deleteTradingHistory = newDeleteTradingHistory() + thisObject.deleteTradingHistory.initialize() - function initialize() { + thisObject.chartAspectRatio = newChartAspectRatio() + thisObject.chartAspectRatio.initialize() - thisObject.deleteTradingHistory = newDeleteTradingHistory(); - thisObject.deleteTradingHistory.initialize(); + thisObject.playStopButton = newPlayStopButton() + thisObject.playStopButton.initialize() - thisObject.chartAspectRatio = newChartAspectRatio(); - thisObject.chartAspectRatio.initialize(); + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } - thisObject.playStopButton = newPlayStopButton(); - thisObject.playStopButton.initialize(); + function resize () { + container.frame.position.x = 0 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + thisObject.container.frame.width = browserCanvas.width + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT + } - } + function getContainer (point) { + let container - function resize() { + container = thisObject.deleteTradingHistory.getContainer(point) + if (container !== undefined) { return container } - container.frame.position.x = 0; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + container = thisObject.chartAspectRatio.getContainer(point) + if (container !== undefined) { return container } - thisObject.container.frame.width = browserCanvas.width; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; - - } - - function getContainer(point) { - - let container; - - container = thisObject.deleteTradingHistory.getContainer(point); - if (container !== undefined) { return container; } - - container = thisObject.chartAspectRatio.getContainer(point); - if (container !== undefined) { return container; } - - container = thisObject.playStopButton.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.playStopButton.getContainer(point) + if (container !== undefined) { return container } /* The point does not belong to any inner container, so we return the current container. */ - return thisObject.container; + return thisObject.container + } + function draw () { + thisObject.container.frame.draw(false, false) + + drawBackground() + thisObject.deleteTradingHistory.draw() + thisObject.chartAspectRatio.draw() + thisObject.playStopButton.draw() + } + + function drawBackground () { + let opacity = 1 + + let zeroPoint = { + x: 0, + y: 0 } - function draw() { + zeroPoint = thisObject.container.frame.frameThisPoint(zeroPoint) - thisObject.container.frame.draw(false, false); + let breakpointsHeight = 15 + const RED_LINE_HIGHT = 5 - drawBackground(); - thisObject.deleteTradingHistory.draw(); - thisObject.chartAspectRatio.draw(); - thisObject.playStopButton.draw(); + browserCanvasContext.beginPath() + browserCanvasContext.rect(zeroPoint.x, zeroPoint.y + breakpointsHeight, thisObject.container.frame.width, thisObject.container.frame.height) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', ' + opacity + ')' + browserCanvasContext.closePath() + browserCanvasContext.fill() - } - - function drawBackground() { - - let opacity = 1; - - let zeroPoint = { - x: 0, - y: 0 - }; - - zeroPoint = thisObject.container.frame.frameThisPoint(zeroPoint); - - let breakpointsHeight = 15; - const RED_LINE_HIGHT = 5; - - browserCanvasContext.beginPath(); - browserCanvasContext.rect(zeroPoint.x, zeroPoint.y + breakpointsHeight, thisObject.container.frame.width, thisObject.container.frame.height ); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', ' + opacity + ')'; - browserCanvasContext.closePath(); - browserCanvasContext.fill(); - - browserCanvasContext.beginPath(); - browserCanvasContext.rect(zeroPoint.x, zeroPoint.y + breakpointsHeight, thisObject.container.frame.width,RED_LINE_HIGHT); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', ' + opacity + ')'; - browserCanvasContext.closePath(); - browserCanvasContext.fill(); - } -} \ No newline at end of file + browserCanvasContext.beginPath() + browserCanvasContext.rect(zeroPoint.x, zeroPoint.y + breakpointsHeight, thisObject.container.frame.width, RED_LINE_HIGHT) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', ' + opacity + ')' + browserCanvasContext.closePath() + browserCanvasContext.fill() + } +} diff --git a/Spaces/ChartSpace.js b/Spaces/ChartSpace.js index ef6c55184..332d61f3d 100644 --- a/Spaces/ChartSpace.js +++ b/Spaces/ChartSpace.js @@ -1,132 +1,117 @@ -/* + /* The chart space is where all the charts live. What this space contains is a type of object we call Time Machine. A Time Machine is a cointainer of -charts objects. The idea is simple, all the chart objects are ploted according to the time of the Time Machine object. When the time of the Time Machine +charts objects. The idea is simple, all the chart objects are ploted according to the time of the Time Machine object. When the time of the Time Machine changes, then all charts in it are replotted with the corresponging data. */ -function newChartSpace() { +function newChartSpace () { + const MODULE_NAME = 'Chart Space' + const INFO_LOG = false + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Chart Space"; - const INFO_LOG = false; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + var thisObject = { + container: undefined, + draw: draw, + timeMachines: [], + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - draw: draw, - timeMachines: [], - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container + thisObject.container.frame.width = CHART_SPACE_WIDTH + thisObject.container.frame.height = CHART_SPACE_HEIGHT - var container = newContainer(); - container.initialize(); - thisObject.container = container; + container.displacement.containerName = 'Chart Space' + container.frame.containerName = 'Chart Space' - thisObject.container.frame.width = CHART_SPACE_WIDTH; - thisObject.container.frame.height = CHART_SPACE_HEIGHT; + container.frame.position.x = browserCanvas.width / 2 - thisObject.container.frame.width / 2 + container.frame.position.y = browserCanvas.height / 2 - thisObject.container.frame.height / 2 - container.displacement.containerName = "Chart Space"; - container.frame.containerName = "Chart Space"; + container.isDraggeable = false - container.frame.position.x = browserCanvas.width / 2 - thisObject.container.frame.width / 2; - container.frame.position.y = browserCanvas.height / 2 - thisObject.container.frame.height / 2; + return thisObject - container.isDraggeable = false; + function initialize (callBackFunction) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } - return thisObject; - - function initialize(callBackFunction) { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - - let initializedCounter = 0; - let toInitialize = 1; + let initializedCounter = 0 + let toInitialize = 1 /* We create the first of many possible time machines that could live at the Chart Space. */ - var timeMachine = newTimeMachine(); + var timeMachine = newTimeMachine() - timeMachine.container.displacement.parentDisplacement = this.container.displacement; - timeMachine.container.frame.parentFrame = this.container.frame; + timeMachine.container.displacement.parentDisplacement = this.container.displacement + timeMachine.container.frame.parentFrame = this.container.frame - timeMachine.container.parentContainer = this.container; + timeMachine.container.parentContainer = this.container /* We make the time machine a little bit smaller than the current space. */ - timeMachine.container.frame.width = this.container.frame.width * 1; - timeMachine.container.frame.height = this.container.frame.height * 1; + timeMachine.container.frame.width = this.container.frame.width * 1 + timeMachine.container.frame.height = this.container.frame.height * 1 - timeMachine.container.frame.position.x = this.container.frame.width / 2 - timeMachine.container.frame.width / 2; - timeMachine.container.frame.position.y = this.container.frame.height / 2 - timeMachine.container.frame.height / 2; + timeMachine.container.frame.position.x = this.container.frame.width / 2 - timeMachine.container.frame.width / 2 + timeMachine.container.frame.position.y = this.container.frame.height / 2 - timeMachine.container.frame.height / 2 - timeMachine.initialize(onTimeMachineInitialized); + timeMachine.initialize(onTimeMachineInitialized) - function onTimeMachineInitialized(err) { + function onTimeMachineInitialized (err) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onTimeMachineInitialized -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onTimeMachineInitialized -> Entering function."); } + initializedCounter++ - initializedCounter++; + if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onTimeMachineInitialized -> Initialization of a Time Machine failed.') } - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + callBackFunction(err) + return + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onTimeMachineInitialized -> Initialization of a Time Machine failed."); } + thisObject.timeMachines.push(timeMachine) - callBackFunction(err); - return; - } - - thisObject.timeMachines.push(timeMachine); - - if (initializedCounter === toInitialize) { - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - } - } + if (initializedCounter === toInitialize) { + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + } } + } - function draw() { - - thisObject.container.frame.draw(false, false); + function draw () { + thisObject.container.frame.draw(false, false) /* When we draw the chart space, that means we draw all the time machines in it. */ - for (var i = 0; i < thisObject.timeMachines.length; i++ ) { - - var timeMachine = thisObject.timeMachines[i]; - timeMachine.draw(); - - } - + for (var i = 0; i < thisObject.timeMachines.length; i++) { + var timeMachine = thisObject.timeMachines[i] + timeMachine.draw() } + } - function getContainer(point) { + function getContainer (point) { + if (INFO_LOG === true) { logger.write('[INFO] getContainer -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getContainer -> Entering function."); } - - let container; + let container /* Now we see which is the inner most container that has it */ - for (var i = 0; i < this.timeMachines.length; i++) { - - container = this.timeMachines[i].getContainer(point); - - if (container !== undefined) { + for (var i = 0; i < this.timeMachines.length; i++) { + container = this.timeMachines[i].getContainer(point) + if (container !== undefined) { /* We found an inner container which has the point. We return it. */ - return container; - } - } + return container + } + } /* The point does not belong to any inner container, so we return the current container. */ - return this.container; - - } -} \ No newline at end of file + return this.container + } +} diff --git a/Spaces/FloatingSpace.js b/Spaces/FloatingSpace.js index a1d20901d..1bd06335c 100644 --- a/Spaces/FloatingSpace.js +++ b/Spaces/FloatingSpace.js @@ -1,44 +1,36 @@ - -function newFloatingSpace() { - +  +function newFloatingSpace () { /* The Floating Space is the place where floating elements like floatingObjects, live and are rendered. This space has its own physics which helps with the animation of these objects and also preventing them to overlap. */ - let thisObject = { - floatingLayer: undefined, // This is the array of floatingObjects being displayed - profileBalls: undefined, - noteSets: undefined, - initialize: initialize - }; + let thisObject = { + floatingLayer: undefined, // This is the array of floatingObjects being displayed + profileBalls: undefined, + noteSets: undefined, + initialize: initialize + } - return thisObject; + return thisObject - function initialize(callBackFunction) { + function initialize (callBackFunction) { + thisObject.floatingLayer = newFloatingLayer() + thisObject.floatingLayer.initialize(onFloatingLayerInitialized) - thisObject.floatingLayer = newFloatingLayer(); - thisObject.floatingLayer.initialize(onFloatingLayerInitialized); + function onFloatingLayerInitialized (err) { + thisObject.profileBalls = newProfileBalls() + thisObject.profileBalls.initialize(thisObject.floatingLayer, onProfileBallsInitialized) - function onFloatingLayerInitialized(err) { + function onProfileBallsInitialized (err) { + thisObject.noteSets = newNoteSets() + thisObject.noteSets.initialize(thisObject.floatingLayer, onNoteSetsInitialized) - thisObject.profileBalls = newProfileBalls(); - thisObject.profileBalls.initialize(thisObject.floatingLayer, onProfileBallsInitialized); + function onNoteSetsInitialized (err) { - function onProfileBallsInitialized(err) { - - thisObject.noteSets = newNoteSets(); - thisObject.noteSets.initialize(thisObject.floatingLayer, onNoteSetsInitialized); - - function onNoteSetsInitialized(err) { - - - - - } - } } + } } + } } - diff --git a/Spaces/PanelsSpace.js b/Spaces/PanelsSpace.js index f2adebdd0..4869b8366 100644 --- a/Spaces/PanelsSpace.js +++ b/Spaces/PanelsSpace.js @@ -1,114 +1,104 @@ -/* + /* -The Panel Space y the place wehre all panels live, no matter who create them. +The Panel Space y the place wehre all panels live, no matter who create them. */ -function newPanelsSpace() { +function newPanelsSpace () { + var thisObject = { + container: undefined, + createNewPanel: createNewPanel, + destroyPanel: destroyPanel, + getPanel: getPanel, + draw: draw, + panels: [], + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - createNewPanel: createNewPanel, - destroyPanel: destroyPanel, - getPanel: getPanel, - draw: draw, - panels: [], - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container + thisObject.container.isDraggeable = false - var container = newContainer(); - container.initialize(); - thisObject.container = container; - thisObject.container.isDraggeable = false; + container.displacement.containerName = 'Panels Space' + container.frame.containerName = 'Panels Space' - container.displacement.containerName = "Panels Space"; - container.frame.containerName = "Panels Space"; + return thisObject - return thisObject; - - function initialize() { + function initialize () { /* The space does not create any Panels for itself, it just sits and waits others need panels. */ - } + } - function createNewPanel(pType, pParameters) { + function createNewPanel (pType, pParameters) { + let panel - let panel; + switch (pType) { - switch (pType) { - - case "Time Control Panel": - { - panel = newTimeControlPanel(); - panel.initialize(); - break; - } - - case "Products Panel": - { - panel = newProductsPanel(); - panel.initialize(); - break; - } - case "Plotter Panel": - { - panel = getNewPlotterPanel(pParameters.devTeam, pParameters.plotterCodeName, pParameters.moduleCodeName, pParameters.panelCodeName); - panel.initialize(); - break; - } + case 'Time Control Panel': + { + panel = newTimeControlPanel() + panel.initialize() + break } - thisObject.panels.push(panel); - - panel.handle = Math.floor((Math.random() * 10000000) + 1); - - return panel.handle; - } - - function destroyPanel(pPanelHandle) { - - for (let i = 0; i < thisObject.panels.length; i++) { - - let panel = thisObject.panels[i]; - - if (panel.handle === pPanelHandle) { - thisObject.panels.splice(i, 1); // Delete item from array. - return; - } + case 'Products Panel': + { + panel = newProductsPanel() + panel.initialize() + break + } + case 'Plotter Panel': + { + panel = getNewPlotterPanel(pParameters.devTeam, pParameters.plotterCodeName, pParameters.moduleCodeName, pParameters.panelCodeName) + panel.initialize() + break } } - function getPanel(pPanelHandle) { + thisObject.panels.push(panel) - for (let i = 0; i < thisObject.panels.length; i++) { + panel.handle = Math.floor((Math.random() * 10000000) + 1) - let panel = thisObject.panels[i]; + return panel.handle + } - if (panel.handle === pPanelHandle) { - return panel; - } - } + function destroyPanel (pPanelHandle) { + for (let i = 0; i < thisObject.panels.length; i++) { + let panel = thisObject.panels[i] + + if (panel.handle === pPanelHandle) { + thisObject.panels.splice(i, 1) // Delete item from array. + return + } } + } - function draw() { + function getPanel (pPanelHandle) { + for (let i = 0; i < thisObject.panels.length; i++) { + let panel = thisObject.panels[i] - thisObject.container.frame.draw(false, false); + if (panel.handle === pPanelHandle) { + return panel + } + } + } + + function draw () { + thisObject.container.frame.draw(false, false) /* When we draw a time machine, that means also to draw all the charts in it. */ - for (var i = 0; i < thisObject.panels.length; i++) { - - let panel = thisObject.panels[i]; - panel.draw(); - - } + for (var i = 0; i < thisObject.panels.length; i++) { + let panel = thisObject.panels[i] + panel.draw() } + } - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* @@ -117,21 +107,18 @@ function newPanelsSpace() { */ - for (var i = thisObject.panels.length - 1; i >= 0; i--) { - - container = thisObject.panels[i].getContainer(point); - - if (container !== undefined) { + for (var i = thisObject.panels.length - 1; i >= 0; i--) { + container = thisObject.panels[i].getContainer(point) + if (container !== undefined) { /* We found an inner container which has the point. We return it. */ - return container; - } - } + return container + } + } /* The point does not belong to any inner container, so we return the current container. */ - return thisObject.container; - - } -} \ No newline at end of file + return thisObject.container + } +} diff --git a/Spaces/TopSpace.js b/Spaces/TopSpace.js index 52ae3d410..71dd40717 100644 --- a/Spaces/TopSpace.js +++ b/Spaces/TopSpace.js @@ -1,132 +1,120 @@ - -function newTopSpace() { +  +function newTopSpace () { + var thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + companyLogo: undefined, + endUser: undefined, + devTeam: undefined, + currentBot: undefined, + currentProcess: undefined, + currentStartMode: undefined, + login: undefined, + initialize: initialize + } - var thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - companyLogo: undefined, - endUser: undefined, - devTeam: undefined, - currentBot: undefined, - currentProcess: undefined, - currentStartMode: undefined, - login: undefined, - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container - var container = newContainer(); - container.initialize(); - thisObject.container = container; + resize() - resize(); + container.isDraggeable = false - container.isDraggeable = false; + return thisObject - return thisObject; - - function initialize() { - - let sharedStatus = { - currentDevTeamIndex: 0, - currentUserBotIndex: 0, - currentProcessIndex: 0, - currentBotType: "", - eventHandler: newEventHandler() - }; - - thisObject.login = newLogin(); - thisObject.login.initialize(onLoginInitialized); - - thisObject.companyLogo = newCompanyLogo(); - thisObject.endUser = newEndUser(); - thisObject.currentBot = newCurrentBot(); - thisObject.currentProcess = newCurrentProcess(); - thisObject.currentStartMode = newCurrentStartMode(); - thisObject.devTeam = newDevTeam(); - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); - - function onLoginInitialized() { - - thisObject.companyLogo.initialize(); - thisObject.endUser.initialize(); - thisObject.currentBot.initialize(sharedStatus); - thisObject.currentProcess.initialize(sharedStatus); - thisObject.currentStartMode.initialize(sharedStatus); - thisObject.devTeam.initialize(sharedStatus); - - } + function initialize () { + let sharedStatus = { + currentDevTeamIndex: 0, + currentUserBotIndex: 0, + currentProcessIndex: 0, + currentBotType: '', + eventHandler: newEventHandler() } - function resize() { + thisObject.login = newLogin() + thisObject.login.initialize(onLoginInitialized) - thisObject.container.frame.width = browserCanvas.width; - thisObject.container.frame.height = TOP_SPACE_HEIGHT; + thisObject.companyLogo = newCompanyLogo() + thisObject.endUser = newEndUser() + thisObject.currentBot = newCurrentBot() + thisObject.currentProcess = newCurrentProcess() + thisObject.currentStartMode = newCurrentStartMode() + thisObject.devTeam = newDevTeam() - container.frame.position.x = 0; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + function onLoginInitialized () { + thisObject.companyLogo.initialize() + thisObject.endUser.initialize() + thisObject.currentBot.initialize(sharedStatus) + thisObject.currentProcess.initialize(sharedStatus) + thisObject.currentStartMode.initialize(sharedStatus) + thisObject.devTeam.initialize(sharedStatus) } + } - function getContainer(point) { + function resize () { + thisObject.container.frame.width = browserCanvas.width + thisObject.container.frame.height = TOP_SPACE_HEIGHT - let container; + container.frame.position.x = 0 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } - container = thisObject.companyLogo.getContainer(point); - if (container !== undefined) { return container; } + function getContainer (point) { + let container - container = thisObject.endUser.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.companyLogo.getContainer(point) + if (container !== undefined) { return container } - container = thisObject.devTeam.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.endUser.getContainer(point) + if (container !== undefined) { return container } - container = thisObject.currentBot.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.devTeam.getContainer(point) + if (container !== undefined) { return container } - container = thisObject.currentProcess.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.currentBot.getContainer(point) + if (container !== undefined) { return container } - container = thisObject.currentStartMode.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.currentProcess.getContainer(point) + if (container !== undefined) { return container } - container = thisObject.login.getContainer(point); - if (container !== undefined) { return container; } + container = thisObject.currentStartMode.getContainer(point) + if (container !== undefined) { return container } + + container = thisObject.login.getContainer(point) + if (container !== undefined) { return container } /* The point does not belong to any inner container, so we return the current container. */ - return thisObject.container; + return thisObject.container + } - } + function draw () { + thisObject.container.frame.draw(false, false) - function draw() { + drawBackground() + thisObject.companyLogo.draw() + thisObject.endUser.draw() + thisObject.devTeam.draw() + thisObject.currentBot.draw() + thisObject.currentProcess.draw() + thisObject.currentStartMode.draw() + thisObject.login.draw() + } - thisObject.container.frame.draw(false, false); + function drawBackground () { + let opacity = 1 - drawBackground(); - thisObject.companyLogo.draw(); - thisObject.endUser.draw(); - thisObject.devTeam.draw(); - thisObject.currentBot.draw(); - thisObject.currentProcess.draw(); - thisObject.currentStartMode.draw(); - thisObject.login.draw(); + browserCanvasContext.beginPath() - } + browserCanvasContext.rect(0, 0, thisObject.container.frame.width, thisObject.container.frame.height) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', ' + opacity + ')' - function drawBackground() { + browserCanvasContext.closePath() - let opacity = 1; - - browserCanvasContext.beginPath(); - - browserCanvasContext.rect(0, 0, thisObject.container.frame.width, thisObject.container.frame.height); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', ' + opacity + ')'; - - browserCanvasContext.closePath(); - - browserCanvasContext.fill(); - - } -} \ No newline at end of file + browserCanvasContext.fill() + } +} diff --git a/SplashScreen.js b/SplashScreen.js index 1e1684d34..791ec78a4 100644 --- a/SplashScreen.js +++ b/SplashScreen.js @@ -1,180 +1,158 @@ -/* + /* The Splash Screen is to show some 'loading...' controls while the app is being loaded on the background. After the loading is complete the Splash Screens dissapears for good. */ -function newSplashScreen() { +function newSplashScreen () { + var thisObject = { + container: undefined, + draw: draw, + timeMachines: [], + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - draw: draw, - timeMachines: [], - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container + resize() - var container = newContainer(); - container.initialize(); - thisObject.container = container; + container.displacement.containerName = 'Splash Screen' + container.frame.containerName = 'Splash Screen' - resize(); + container.frame.position.x = 0 + container.frame.position.y = 0 - container.displacement.containerName = "Splash Screen"; - container.frame.containerName = "Splash Screen"; + container.isDraggeable = false - container.frame.position.x = 0; - container.frame.position.y = 0; + let fadeOutCounter = 0 + let opacity = 1 - container.isDraggeable = false; + let logo + let canDrawLogo = false + return thisObject - let fadeOutCounter = 0; - let opacity = 1; + function initialize () { + logo = new Image() - let logo; - let canDrawLogo = false; - - return thisObject; - - function initialize() { - - logo = new Image(); - - logo.onload = onImageLoad; - - function onImageLoad() { - canDrawLogo = true; - } - - logo.src = window.canvasApp.urlPrefix + "Images/aa-logo.png"; - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + logo.onload = onImageLoad + function onImageLoad () { + canDrawLogo = true } - function resize() { + logo.src = window.canvasApp.urlPrefix + 'Images/aa-logo.png' - thisObject.container.frame.width = browserCanvas.width; - thisObject.container.frame.height = browserCanvas.height; + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } + function resize () { + thisObject.container.frame.width = browserCanvas.width + thisObject.container.frame.height = browserCanvas.height + } + + function draw () { + if (splashScreenNeeded === false) { + stepsInitializationCounter = 100 + + fadeOutCounter++ + + if (fadeOutCounter > 20) { + return + } + opacity = opacity - 0.1 } - - function draw() { - - if (splashScreenNeeded === false) { - - stepsInitializationCounter = 100; - - fadeOutCounter++; - - if (fadeOutCounter > 20) { - return; - } - opacity = opacity - 0.1; - } - - thisObject.container.frame.draw(false, false); + thisObject.container.frame.draw(false, false) /* Set the background. */ - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - browserCanvasContext.rect(0, 0, thisObject.container.frame.width, thisObject.container.frame.height); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'; + browserCanvasContext.rect(0, 0, thisObject.container.frame.width, thisObject.container.frame.height) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')' - browserCanvasContext.closePath(); + browserCanvasContext.closePath() - browserCanvasContext.fill(); + browserCanvasContext.fill() - if (canDrawLogo === false) { return; } + if (canDrawLogo === false) { return } /* First the AA Logo. */ - let imageHeight = 96; - let imageWidth = 480; - let yDisplacement = -50; + let imageHeight = 96 + let imageWidth = 480 + let yDisplacement = -50 - let imagePoint = { - x: thisObject.container.frame.width * 1 / 2 - imageWidth / 2, - y: thisObject.container.frame.height * 1 / 2 - imageHeight / 2 + yDisplacement - }; + let imagePoint = { + x: thisObject.container.frame.width * 1 / 2 - imageWidth / 2, + y: thisObject.container.frame.height * 1 / 2 - imageHeight / 2 + yDisplacement + } - imagePoint = thisObject.container.frame.frameThisPoint(imagePoint); + imagePoint = thisObject.container.frame.frameThisPoint(imagePoint) - browserCanvasContext.drawImage(logo, imagePoint.x, imagePoint.y, imageWidth, imageHeight); + browserCanvasContext.drawImage(logo, imagePoint.x, imagePoint.y, imageWidth, imageHeight) /* Second the % of Advance. */ - let label = '' + Math.trunc(stepsInitializationCounter) + ' %'; - stepsInitializationCounter = stepsInitializationCounter + 0.5; + let label = '' + Math.trunc(stepsInitializationCounter) + ' %' + stepsInitializationCounter = stepsInitializationCounter + 0.5 - if (stepsInitializationCounter > 99) { + if (stepsInitializationCounter > 99) { + splashScreenNeeded = false + stepsInitializationCounter = 99 + } - splashScreenNeeded = false; - stepsInitializationCounter = 99; - } + let fontSize = 10 + let labelPoint = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO - 25, + y: thisObject.container.frame.height / 2 + fontSize / 2 + fontSize * 0.1 + 80 + yDisplacement + } - let fontSize = 10; + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')' + browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) - let labelPoint = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO - 25, - y: thisObject.container.frame.height / 2 + fontSize / 2 + fontSize * 0.1 + 80 + yDisplacement - }; - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')'; - browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y); - - let title; - let titlePoint; + let title + let titlePoint /* Algo Bots Competitions Sub Title */ - fontSize = 15; + fontSize = 15 - title = "Trading Bots Competitions Platform" + title = 'Trading Bots Competitions Platform' - titlePoint = { - x: thisObject.container.frame.width / 2 - title.length / 2 * fontSize * FONT_ASPECT_RATIO - 20, - y: thisObject.container.frame.height / 2 - fontSize * 2 + 80 + yDisplacement - }; - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')'; - browserCanvasContext.fillText(title, titlePoint.x, titlePoint.y); - - + titlePoint = { + x: thisObject.container.frame.width / 2 - title.length / 2 * fontSize * FONT_ASPECT_RATIO - 20, + y: thisObject.container.frame.height / 2 - fontSize * 2 + 80 + yDisplacement } + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')' + browserCanvasContext.fillText(title, titlePoint.x, titlePoint.y) + } - - function getContainer(point) { - - var container; + function getContainer (point) { + var container /* First we check if this point is inside this space. */ - if (this.container.frame.isThisPointHere(point) === true) { - + if (this.container.frame.isThisPointHere(point) === true) { /* Now we see which is the inner most container that has it */ // add validation of inner most containers here. /* The point does not belong to any inner container, so we return the current container. */ - return this.container; - - } else { - + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } - -} \ No newline at end of file + } +} diff --git a/TimeLineCoordinateSystem.js b/TimeLineCoordinateSystem.js index 1de7389e2..0fef5e7b6 100644 --- a/TimeLineCoordinateSystem.js +++ b/TimeLineCoordinateSystem.js @@ -1,4 +1,4 @@ -/* + /* This Object object is responsible for defining the coordinate system in a TimeLine. @@ -7,85 +7,77 @@ The scale on the Y axis depends on the data that wants to be plotted. Usually we */ -function newTimeLineCoordinateSystem() { +function newTimeLineCoordinateSystem () { + var thisObject = { + min: undefined, + max: undefined, + scale: undefined, + transformThisPoint: transformThisPoint, + transformThisPoint2: transformThisPoint2, + unInverseTransform: unInverseTransform, + inverseTransformUncappedY: inverseTransformUncappedY, + initializeX: initializeX, + initializeY: initializeY, + initialize: initialize + } - var thisObject = { - min: undefined, - max: undefined, - scale: undefined, - transformThisPoint: transformThisPoint, - transformThisPoint2: transformThisPoint2, - unInverseTransform: unInverseTransform, - inverseTransformUncappedY: inverseTransformUncappedY, - initializeX: initializeX, - initializeY: initializeY, - initialize: initialize - }; + var min = { + x: 0, + y: 0 + } - var min = { - x: 0, - y: 0 - }; + var max = { + x: 0, + y: 0 + } - var max = { - x: 0, - y: 0 - }; + var scale = { + x: 0, + y: 0 + } - var scale = { - x: 0, - y: 0 - }; + thisObject.min = min + thisObject.max = max + thisObject.scale = scale - thisObject.min = min; - thisObject.max = max; - thisObject.scale = scale; + let maxHeight - let maxHeight; - - return thisObject; - - function initialize(minValue, maxValue, maxWidth, pMaxHeight) { + return thisObject + function initialize (minValue, maxValue, maxWidth, pMaxHeight) { /* Defines the min and max value of rate that we are going to transport to the available screen at the center position. */ - thisObject.min.x = minValue.x; // * 0.999; // 0.1% less - thisObject.max.x = maxValue.x; // * 1.001; // 0.1% more + thisObject.min.x = minValue.x // * 0.999; // 0.1% less + thisObject.max.x = maxValue.x // * 1.001; // 0.1% more - thisObject.min.y = minValue.y; // * 0.999; // 0.1% less - thisObject.max.y = maxValue.y; // * 1.001; // 0.1% more + thisObject.min.y = minValue.y // * 0.999; // 0.1% less + thisObject.max.y = maxValue.y // * 1.001; // 0.1% more /* Defines the initial Zoom level at center position. */ - thisObject.scale.x = maxWidth / (thisObject.max.x - thisObject.min.x); - thisObject.scale.y = pMaxHeight / (thisObject.max.y - thisObject.min.y); + thisObject.scale.x = maxWidth / (thisObject.max.x - thisObject.min.x) + thisObject.scale.y = pMaxHeight / (thisObject.max.y - thisObject.min.y) - maxHeight = pMaxHeight; + maxHeight = pMaxHeight + } - } + function initializeX (minValue, maxValue, maxWidth) { + thisObject.min.x = minValue.x // * 0.999; // 0.1% less + thisObject.max.x = maxValue.x // * 1.001; // 0.1% more - function initializeX(minValue, maxValue, maxWidth) { + thisObject.scale.x = maxWidth / (thisObject.max.x - thisObject.min.x) + } - thisObject.min.x = minValue.x; // * 0.999; // 0.1% less - thisObject.max.x = maxValue.x; // * 1.001; // 0.1% more + function initializeY (minValue, maxValue, pMaxHeight) { + thisObject.min.y = minValue.y // * 0.999; // 0.1% less + thisObject.max.y = maxValue.y // * 1.001; // 0.1% more - thisObject.scale.x = maxWidth / (thisObject.max.x - thisObject.min.x); + thisObject.scale.y = pMaxHeight / (thisObject.max.y - thisObject.min.y) - } - - function initializeY(minValue, maxValue, pMaxHeight) { - - thisObject.min.y = minValue.y; // * 0.999; // 0.1% less - thisObject.max.y = maxValue.y; // * 1.001; // 0.1% more - - thisObject.scale.y = pMaxHeight / (thisObject.max.y - thisObject.min.y); - - maxHeight = pMaxHeight; - } - - - function transformThisPoint(point) { + maxHeight = pMaxHeight + } + function transformThisPoint (point) { /* This is the straigh fordward transformation this object provides. The input is a point on the data set that wants to be plotted in a timeline. @@ -99,59 +91,39 @@ function newTimeLineCoordinateSystem() { */ - point = { - x: (point.x - this.min.x) * this.scale.x, - y: maxHeight - (point.y - this.min.y) * this.scale.y - }; - - return point; + point = { + x: (point.x - this.min.x) * this.scale.x, + y: maxHeight - (point.y - this.min.y) * this.scale.y } + return point + } - function transformThisPoint2(point) { - - point = { - x: (point.x - this.min.x) * this.scale.x, - y: (maxHeight- point.y - this.min.y) * this.scale.y - }; - - return point; + function transformThisPoint2 (point) { + point = { + x: (point.x - this.min.x) * this.scale.x, + y: (maxHeight - point.y - this.min.y) * this.scale.y } + return point + } - function unInverseTransform(point, inverseY) { - - point = { - x: (point.x / this.scale.x) + this.min.x, - y: (inverseY - point.y) / this.scale.y + this.min.y - }; - - return point; + function unInverseTransform (point, inverseY) { + point = { + x: (point.x / this.scale.x) + this.min.x, + y: (inverseY - point.y) / this.scale.y + this.min.y } + return point + } - function inverseTransformUncappedY(point, inverseY) { - - point = { - x: (point.x - this.min.x) * this.scale.x, - y: (inverseY - point.y) * this.scale.y - }; - - return point; + function inverseTransformUncappedY (point, inverseY) { + point = { + x: (point.x - this.min.x) * this.scale.x, + y: (inverseY - point.y) * this.scale.y } - - - + return point + } } - - - - - - - - - - diff --git a/TimeMachine.js b/TimeMachine.js index c03040d15..499ca9a9c 100644 --- a/TimeMachine.js +++ b/TimeMachine.js @@ -1,180 +1,166 @@ -/* + /* Markets are a function of time. When watching them, end users must be positioned at one particular point in time. The system currently allows users to position themselves at any time they like. In the future, it will be usefull to explore markets and compare them at different times simultaneously. Anticipating that future this module exists. All the charts that depand on a datetime are children of this object Time Machine. In the future we will allow users to have more than one Time Machine, -each one with it own charts, and each one positioned at an especific point in titme. +each one with it own charts, and each one positioned at an especific point in titme. */ -function newTimeMachine() { +function newTimeMachine () { + const MODULE_NAME = 'Time Machine' + const INFO_LOG = false + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Time Machine"; - const INFO_LOG = false; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let thisObject = { + container: undefined, + draw: draw, + charts: [], + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - charts: [], - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container + thisObject.container.isDraggeable = false - let container = newContainer(); - container.initialize(); - thisObject.container = container; - thisObject.container.isDraggeable = false; + container.displacement.containerName = 'Time Machine' + container.frame.containerName = 'Time Machine' - container.displacement.containerName = "Time Machine"; - container.frame.containerName = "Time Machine"; + let controlPanelHandle // We need this to destroy the Panel when this object is itself destroyed or no longer needs it... + let productsPanelHandle // ... also to request a reference to the object for the cases we need it. - let controlPanelHandle; // We need this to destroy the Panel when this object is itself destroyed or no longer needs it... - let productsPanelHandle; // ... also to request a reference to the object for the cases we need it. + return thisObject - return thisObject; - - function initialize(callBackFunction) { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function initialize (callBackFunction) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } /* Each Time Machine has a Control Panel. */ - controlPanelHandle = canvas.panelsSpace.createNewPanel("Time Control Panel"); - let controlPanel = canvas.panelsSpace.getPanel(controlPanelHandle); + controlPanelHandle = canvas.panelsSpace.createNewPanel('Time Control Panel') + let controlPanel = canvas.panelsSpace.getPanel(controlPanelHandle) - productsPanelHandle = canvas.panelsSpace.createNewPanel("Products Panel"); - let productsPanel = canvas.panelsSpace.getPanel(productsPanelHandle); + productsPanelHandle = canvas.panelsSpace.createNewPanel('Products Panel') + let productsPanel = canvas.panelsSpace.getPanel(productsPanelHandle) - let iteration = 0; + let iteration = 0 /* First, we initialize the market that we are going to show first on screen. Later all the other markets will be initialized on the background. */ - let timelineChart = newTimelineChart(); + let timelineChart = newTimelineChart() - timelineChart.container.displacement.parentDisplacement = thisObject.container.displacement; - timelineChart.container.frame.parentFrame = thisObject.container.frame; + timelineChart.container.displacement.parentDisplacement = thisObject.container.displacement + timelineChart.container.frame.parentFrame = thisObject.container.frame - timelineChart.container.parentContainer = thisObject.container; + timelineChart.container.parentContainer = thisObject.container - timelineChart.container.frame.width = thisObject.container.frame.width * 1; - timelineChart.container.frame.height = thisObject.container.frame.height * 1 * canvas.bottomSpace.chartAspectRatio.aspectRatio.y; + timelineChart.container.frame.width = thisObject.container.frame.width * 1 + timelineChart.container.frame.height = thisObject.container.frame.height * 1 * canvas.bottomSpace.chartAspectRatio.aspectRatio.y - timelineChart.container.frame.position.x = thisObject.container.frame.width / 2 - timelineChart.container.frame.width / 2; - timelineChart.container.frame.position.y = timelineChart.container.frame.height * 1.5 * iteration; + timelineChart.container.frame.position.x = thisObject.container.frame.width / 2 - timelineChart.container.frame.width / 2 + timelineChart.container.frame.position.y = timelineChart.container.frame.height * 1.5 * iteration - timelineChart.initialize(productsPanel, onDefaultMarketInitialized); + timelineChart.initialize(productsPanel, onDefaultMarketInitialized) - iteration++; + iteration++ - function onDefaultMarketInitialized(err) { + function onDefaultMarketInitialized (err) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDefaultMarketInitialized -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDefaultMarketInitialized -> Entering function."); } + if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onDefaultMarketInitialized -> Initialization of the only market failed.') } - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + callBackFunction(err) + return + } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onDefaultMarketInitialized -> Initialization of the only market failed."); } + thisObject.charts.push(timelineChart) - callBackFunction(err); - return; - } + controlPanel.container.eventHandler.listenToEvent('Datetime Changed', timelineChart.setDatetime, undefined) + timelineChart.container.eventHandler.listenToEvent('Datetime Changed', controlPanel.setDatetime) - thisObject.charts.push(timelineChart); + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) - controlPanel.container.eventHandler.listenToEvent('Datetime Changed', timelineChart.setDatetime, undefined); - timelineChart.container.eventHandler.listenToEvent('Datetime Changed', controlPanel.setDatetime); - - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - - //initializeTheRestOfTheMarkets(); - - } - - function initializeTheRestOfTheMarkets() { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> initializeTheRestOfTheMarkets -> Entering function."); } - - markets.forEach(initializeTimelineChart); - - function initializeTimelineChart(item, key, mapObj) { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> initializeTheRestOfTheMarkets -> initializeTimelineChart -> Entering function."); } - - if (key === INITIAL_DEFAULT_MARKET) { // We skip this market since it has already been initialized. - - return; - } - - let timelineChart = newTimelineChart(); - - timelineChart.container.displacement.parentDisplacement = thisObject.container.displacement; - timelineChart.container.frame.parentFrame = thisObject.container.frame; - - timelineChart.container.parentContainer = thisObject.container; - - timelineChart.container.frame.width = thisObject.container.frame.width * 1; - timelineChart.container.frame.height = thisObject.container.frame.height * 1 * canvas.bottomSpace.chartAspectRatio.aspectRatio.y; - - timelineChart.container.frame.position.x = thisObject.container.frame.width / 2 - timelineChart.container.frame.width / 2; - timelineChart.container.frame.position.y = timelineChart.container.frame.height * 1.5 * iteration; - - timelineChart.initialize(productsPanel, finalSteps); - - iteration++; - - function finalSteps() { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> initializeTheRestOfTheMarkets -> initializeTimelineChart -> finalSteps -> Entering function."); } - - thisObject.charts.push(timelineChart); - - controlPanel.container.eventHandler.listenToEvent('Datetime Changed', timelineChart.setDatetime, undefined); - timelineChart.container.eventHandler.listenToEvent('Datetime Changed', controlPanel.setDatetime); - - } - } - } + // initializeTheRestOfTheMarkets(); } - function draw() { + function initializeTheRestOfTheMarkets () { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> initializeTheRestOfTheMarkets -> Entering function.') } - this.container.frame.draw(false, false); + markets.forEach(initializeTimelineChart) + + function initializeTimelineChart (item, key, mapObj) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> initializeTheRestOfTheMarkets -> initializeTimelineChart -> Entering function.') } + + if (key === INITIAL_DEFAULT_MARKET) { + // We skip this market since it has already been initialized. + + return + } + + let timelineChart = newTimelineChart() + + timelineChart.container.displacement.parentDisplacement = thisObject.container.displacement + timelineChart.container.frame.parentFrame = thisObject.container.frame + + timelineChart.container.parentContainer = thisObject.container + + timelineChart.container.frame.width = thisObject.container.frame.width * 1 + timelineChart.container.frame.height = thisObject.container.frame.height * 1 * canvas.bottomSpace.chartAspectRatio.aspectRatio.y + + timelineChart.container.frame.position.x = thisObject.container.frame.width / 2 - timelineChart.container.frame.width / 2 + timelineChart.container.frame.position.y = timelineChart.container.frame.height * 1.5 * iteration + + timelineChart.initialize(productsPanel, finalSteps) + + iteration++ + + function finalSteps () { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> initializeTheRestOfTheMarkets -> initializeTimelineChart -> finalSteps -> Entering function.') } + + thisObject.charts.push(timelineChart) + + controlPanel.container.eventHandler.listenToEvent('Datetime Changed', timelineChart.setDatetime, undefined) + timelineChart.container.eventHandler.listenToEvent('Datetime Changed', controlPanel.setDatetime) + } + } + } + } + + function draw () { + this.container.frame.draw(false, false) /* When we draw a time machine, that means also to draw all the charts in it. */ - for (let i = 0; i < this.charts.length; i++) { - - let chart = this.charts[i]; - chart.draw(); - - } + for (let i = 0; i < this.charts.length; i++) { + let chart = this.charts[i] + chart.draw() } + } - function getContainer(point) { + function getContainer (point) { + if (INFO_LOG === true) { logger.write('[INFO] getContainer -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getContainer -> Entering function."); } - - let container; + let container /* Now we see which is the inner most container that has it */ - for (let i = 0; i < this.charts.length; i++) { - - container = this.charts[i].getContainer(point); - - if (container !== undefined) { + for (let i = 0; i < this.charts.length; i++) { + container = this.charts[i].getContainer(point) + if (container !== undefined) { /* We found an inner container which has the point. We return it. */ - return container; - } - } - + return container + } + } + /* The point does not belong to any inner container, so we return the current container. */ - return this.container; - } -} \ No newline at end of file + return this.container + } +} diff --git a/TimelineChart.js b/TimelineChart.js index 46ec6aa42..9e474777a 100644 --- a/TimelineChart.js +++ b/TimelineChart.js @@ -1,226 +1,205 @@ -function newTimelineChart() { + function newTimelineChart () { + const MODULE_NAME = 'Timeline Chart' + const INFO_LOG = false + const INTENSIVE_LOG = false + const ERROR_LOG = true + const logger = newWebDebugLog() + logger.fileName = MODULE_NAME - const MODULE_NAME = "Timeline Chart"; - const INFO_LOG = false; - const INTENSIVE_LOG = false; - const ERROR_LOG = true; - const logger = newWebDebugLog(); - logger.fileName = MODULE_NAME; + let timeLineCoordinateSystem = newTimeLineCoordinateSystem() - let timeLineCoordinateSystem = newTimeLineCoordinateSystem(); + let timePeriod = INITIAL_TIME_PERIOD + let datetime = INITIAL_DATE - let timePeriod = INITIAL_TIME_PERIOD; - let datetime = INITIAL_DATE; + let thisObject = { + setDatetime: setDatetime, + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - setDatetime: setDatetime, - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + container.displacement.containerName = 'Timeline Chart' + container.frame.containerName = 'Timeline Chart' - container.displacement.containerName = "Timeline Chart"; - container.frame.containerName = "Timeline Chart"; + let chartGrid + let breakpointsBar - let chartGrid; - let breakpointsBar; + let initializationReady = false - let initializationReady = false; - - let productsPanel; + let productsPanel /* Background */ - let logoAssetA; - let logoAssetB; - let logoExchange; - let logoAA; - let canDrawLogoA = false; - let canDrawLogoB = false; - let canDrawLogoExchange = false; - let canDrawLogoAA = false; + let logoAssetA + let logoAssetB + let logoExchange + let logoAA + let canDrawLogoA = false + let canDrawLogoB = false + let canDrawLogoExchange = false + let canDrawLogoAA = false - let plotterManager; + let plotterManager - return thisObject; + return thisObject - function initialize(pProductsPanel, callBackFunction) { - - try { - - if (INFO_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + function initialize (pProductsPanel, callBackFunction) { + try { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') } /* We load the logow we will need for the background. */ - logoA = new Image(); - logoB = new Image(); - logoExchange = new Image(); - logoAA = new Image(); + logoA = new Image() + logoB = new Image() + logoExchange = new Image() + logoAA = new Image() - logoA.onload = onImageALoaded; + logoA.onload = onImageALoaded - function onImageALoaded() { - canDrawLogoA = true; - } + function onImageALoaded () { + canDrawLogoA = true + } - logoB.onload = onImageBLoaded; + logoB.onload = onImageBLoaded - function onImageBLoaded() { - canDrawLogoB = true; - } + function onImageBLoaded () { + canDrawLogoB = true + } - logoExchange.onload = onImageExchangeLoaded; + logoExchange.onload = onImageExchangeLoaded - function onImageExchangeLoaded() { - canDrawLogoExchange = true; - } + function onImageExchangeLoaded () { + canDrawLogoExchange = true + } - logoAA.onload = onImageAALoaded; + logoAA.onload = onImageAALoaded - function onImageAALoaded() { - canDrawLogoAA = true; - } + function onImageAALoaded () { + canDrawLogoAA = true + } - logoA.src = window.canvasApp.urlPrefix + "Images/tether-logo-background.png"; - logoB.src = window.canvasApp.urlPrefix + "Images/bitcoin-logo-background.png"; - logoExchange.src = window.canvasApp.urlPrefix + "Images/poloniex-logo-background.png"; - logoAA.src = window.canvasApp.urlPrefix + "Images/aa-logo-background.png"; + logoA.src = window.canvasApp.urlPrefix + 'Images/tether-logo-background.png' + logoB.src = window.canvasApp.urlPrefix + 'Images/bitcoin-logo-background.png' + logoExchange.src = window.canvasApp.urlPrefix + 'Images/poloniex-logo-background.png' + logoAA.src = window.canvasApp.urlPrefix + 'Images/aa-logo-background.png' /* Remember the Products Panel */ - productsPanel = pProductsPanel; + productsPanel = pProductsPanel - chartGrid = newChartGrid(); - chartGrid.initialize(); + chartGrid = newChartGrid() + chartGrid.initialize() - breakpointsBar = newBreakpointsBar(); - breakpointsBar.initialize(container, timeLineCoordinateSystem); + breakpointsBar = newBreakpointsBar() + breakpointsBar.initialize(container, timeLineCoordinateSystem) + + recalculateScale() + + // moveViewPortToCurrentDatetime(); + moveToUserPosition(container, timeLineCoordinateSystem) + timePeriod = INITIAL_TIME_PERIOD + datetime = INITIAL_DATE - recalculateScale(); - - //moveViewPortToCurrentDatetime(); - moveToUserPosition(container, timeLineCoordinateSystem); - timePeriod = INITIAL_TIME_PERIOD; - datetime = INITIAL_DATE; - /* Event Subscriptions - we need this events to be fired first here and then in active Plotters. */ - viewPort.eventHandler.listenToEvent("Offset Changed", onOffsetChanged); - viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged); + viewPort.eventHandler.listenToEvent('Offset Changed', onOffsetChanged) + viewPort.eventHandler.listenToEvent('Zoom Changed', onZoomChanged) /* Initialize the Plotter Manager */ - plotterManager = newPlottersManager(); + plotterManager = newPlottersManager() - plotterManager.container.displacement.parentDisplacement = thisObject.container.displacement; - plotterManager.container.frame.parentFrame = thisObject.container.frame; + plotterManager.container.displacement.parentDisplacement = thisObject.container.displacement + plotterManager.container.frame.parentFrame = thisObject.container.frame - plotterManager.container.parentContainer = thisObject.container; + plotterManager.container.parentContainer = thisObject.container - plotterManager.container.frame.width = thisObject.container.frame.width; - plotterManager.container.frame.height = thisObject.container.frame.height; + plotterManager.container.frame.width = thisObject.container.frame.width + plotterManager.container.frame.height = thisObject.container.frame.height - plotterManager.container.frame.position.x = thisObject.container.frame.position.x; - plotterManager.container.frame.position.y = thisObject.container.frame.position.y; + plotterManager.container.frame.position.x = thisObject.container.frame.position.x + plotterManager.container.frame.position.y = thisObject.container.frame.position.y - plotterManager.initialize(pProductsPanel, onPlotterManagerReady); + plotterManager.initialize(pProductsPanel, onPlotterManagerReady) - function onPlotterManagerReady(err) { + function onPlotterManagerReady (err) { + if (INFO_LOG === true) { logger.write('[INFO] initialize -> onPlotterManagerReady -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] initialize -> onPlotterManagerReady -> Entering function."); } + if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onPlotterManagerReady -> Plotter Manager Initialization Failed. ') } + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> onPlotterManagerReady -> err.message = ' + err.message) } - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + return + } - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onPlotterManagerReady -> Plotter Manager Initialization Failed. "); } - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> onPlotterManagerReady -> err.message = " + err.message); } + initializationReady = true + callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) + return + } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - return; - } + canvas.bottomSpace.chartAspectRatio.container.eventHandler.listenToEvent('Chart Aspect Ratio Changed', onAspectRatioChanged) - initializationReady = true; - callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE); - return; - } + function onAspectRatioChanged (pAspectRatio) { + thisObject.container.frame.height = CHART_SPACE_HEIGHT * pAspectRatio.y + recalculateScale() + } + } catch (err) { + if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) } + callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) + } + } - canvas.bottomSpace.chartAspectRatio.container.eventHandler.listenToEvent("Chart Aspect Ratio Changed", onAspectRatioChanged); - - function onAspectRatioChanged(pAspectRatio) { + function onZoomChanged (event) { + if (INFO_LOG === true) { logger.write('[INFO] onZoomChanged -> Entering function.') } - thisObject.container.frame.height = CHART_SPACE_HEIGHT * pAspectRatio.y; - recalculateScale(); + if (initializationReady === true) { + let currentTimePeriod = timePeriod - } - - } catch (err) { - - if (ERROR_LOG === true) { logger.write("[ERROR] initialize -> err = " + err); } - callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE); - } - } - - function onZoomChanged(event) { - - if (INFO_LOG === true) { logger.write("[INFO] onZoomChanged -> Entering function."); } - - if (initializationReady === true) { - - let currentTimePeriod = timePeriod; - - timePeriod = recalculatePeriod(event.newLevel); + timePeriod = recalculatePeriod(event.newLevel) /* If the period changes, we need to spread the word in cascade towards all the depending objects. */ - if (timePeriod !== currentTimePeriod) { + if (timePeriod !== currentTimePeriod) { + plotterManager.setTimePeriod(timePeriod) + } - plotterManager.setTimePeriod(timePeriod); + recalculateCurrentDatetime() - } + saveUserPosition(thisObject.container, timeLineCoordinateSystem) + } + } - recalculateCurrentDatetime(); - - saveUserPosition(thisObject.container, timeLineCoordinateSystem); - - } - } - - function setDatetime(pDatetime) { - - if (INFO_LOG === true) { logger.write("[INFO] setDatetime -> Entering function."); } + function setDatetime (pDatetime) { + if (INFO_LOG === true) { logger.write('[INFO] setDatetime -> Entering function.') } /* This function is used when the time is changed through the user interface, but without zooming or panning. */ /* No matter if the day changed or not, we need to inform all visible Plotters. */ - if (thisObject.container.frame.isInViewPort()) { + if (thisObject.container.frame.isInViewPort()) { + plotterManager.setDatetime(pDatetime) + plotterManager.positionAtDatetime(pDatetime) + breakpointsBar.setDatetime(pDatetime) + } + } - plotterManager.setDatetime(pDatetime); - plotterManager.positionAtDatetime(pDatetime); - breakpointsBar.setDatetime(pDatetime); - } - } + function onOffsetChanged () { + if (INFO_LOG === true) { logger.write('[INFO] onOffsetChanged -> Entering function.') } - function onOffsetChanged() { + if (initializationReady === true) { + if (thisObject.container.frame.isInViewPort()) { + recalculateCurrentDatetime() + saveUserPosition(thisObject.container, timeLineCoordinateSystem) + } + } + } - if (INFO_LOG === true) { logger.write("[INFO] onOffsetChanged -> Entering function."); } - - if (initializationReady === true) { - - if (thisObject.container.frame.isInViewPort()) { - - recalculateCurrentDatetime(); - saveUserPosition(thisObject.container, timeLineCoordinateSystem); - } - } - - } - - function recalculateCurrentDatetime() { - - if (INFO_LOG === true) { logger.write("[INFO] recalculateCurrentDatetime -> Entering function."); } + function recalculateCurrentDatetime () { + if (INFO_LOG === true) { logger.write('[INFO] recalculateCurrentDatetime -> Entering function.') } /* @@ -229,298 +208,263 @@ */ - let center = { - x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2, - y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) / 2 - }; + let center = { + x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2, + y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) / 2 + } - center = unTransformThisPoint(center, thisObject.container); - center = timeLineCoordinateSystem.unInverseTransform(center, thisObject.container.frame.height); + center = unTransformThisPoint(center, thisObject.container) + center = timeLineCoordinateSystem.unInverseTransform(center, thisObject.container.frame.height) - let newDate = new Date(0); - newDate.setUTCSeconds(center.x / 1000); + let newDate = new Date(0) + newDate.setUTCSeconds(center.x / 1000) - datetime = newDate; + datetime = newDate - plotterManager.setDatetime(datetime); + plotterManager.setDatetime(datetime) - breakpointsBar.setDatetime(datetime); + breakpointsBar.setDatetime(datetime) - thisObject.container.eventHandler.raiseEvent("Datetime Changed", datetime); - - } + thisObject.container.eventHandler.raiseEvent('Datetime Changed', datetime) + } - function getContainer(point) { + function getContainer (point) { + if (INFO_LOG === true) { logger.write('[INFO] getContainer -> Entering function.') } - if (INFO_LOG === true) { logger.write("[INFO] getContainer -> Entering function."); } + let container - let container; + container = chartGrid.getContainer(point) - container = chartGrid.getContainer(point); + if (container !== undefined) { return container } - if (container !== undefined) { return container;} + container = breakpointsBar.getContainer(point) - container = breakpointsBar.getContainer(point); + return container + } - return container; + function recalculateScale () { + if (INFO_LOG === true) { logger.write('[INFO] recalculateScale -> Entering function.') } - } + let minValue = { + x: EARLIEST_DATE.valueOf(), + y: 0 + } - function recalculateScale() { + let maxValue = { + x: MAX_PLOTABLE_DATE.valueOf(), + y: nextPorwerOf10(USDT_BTC_HTH) / 4 + } - if (INFO_LOG === true) { logger.write("[INFO] recalculateScale -> Entering function."); } - - let minValue = { - x: EARLIEST_DATE.valueOf(), - y: 0 - }; - - let maxValue = { - x: MAX_PLOTABLE_DATE.valueOf(), - y: nextPorwerOf10(USDT_BTC_HTH) / 4 - }; - - timeLineCoordinateSystem.initialize( + timeLineCoordinateSystem.initialize( minValue, maxValue, thisObject.container.frame.width, thisObject.container.frame.height - ); + ) + } - } + function tooTiny () { + if (INTENSIVE_LOG === true) { logger.write('[INFO] tooTiny -> Entering function.') } - function tooTiny() { + if (viewPort.zoomLevel < Math.trunc(-28.25 * 100) / 100) { + return true + } else { + return false + } + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] tooTiny -> Entering function."); } + function tooSmall () { + if (INFO_LOG === true) { logger.write('[INFO] tooSmall -> Entering function.') } - if (viewPort.zoomLevel < Math.trunc(-28.25 * 100) / 100) { - return true; - } else { - return false; - } + if (viewPort.zoomLevel < Math.trunc(-27.25 * 100) / 100) { + return true + } else { + return false + } + } - } + function draw () { + if (INTENSIVE_LOG === true) { logger.write('[INFO] draw -> Entering function.') } - function tooSmall() { + if (thisObject.container.frame.isInViewPort()) { + this.container.frame.draw() - if (INFO_LOG === true) { logger.write("[INFO] tooSmall -> Entering function."); } + drawBackground() - if (viewPort.zoomLevel < Math.trunc(-27.25 * 100) / 100) { - return true; - } else { - return false; - } + chartGrid.draw(thisObject.container, timeLineCoordinateSystem) - } + plotterManager.draw() - function draw() { + breakpointsBar.draw() + } + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] draw -> Entering function."); } + function drawBackground () { + if (INTENSIVE_LOG === true) { logger.write('[INFO] drawBackground -> Entering function.') } - if (thisObject.container.frame.isInViewPort()) { + if (canDrawLogoA === false || canDrawLogoB === false || canDrawLogoExchange === false || canDrawLogoAA === false) { return } - this.container.frame.draw(); + let backgroundLogoPoint1 + let backgroundLogoPoint2 - drawBackground(); + let imageHeight = 42 + let imageWidth = 150 - chartGrid.draw(thisObject.container, timeLineCoordinateSystem); + let MAX_COLUMNS = 16 + let MAX_ROWS = 7 + let Y_TOP_MARGIN = 30 - plotterManager.draw(); + let point1 = { + x: viewPort.visibleArea.topLeft.x, + y: viewPort.visibleArea.topLeft.y + } - breakpointsBar.draw(); - } - } + backgroundLogoPoint1 = { + x: getDateFromPoint(point1, thisObject.container, timeLineCoordinateSystem).valueOf(), + y: getRateFromPoint(point1, thisObject.container, timeLineCoordinateSystem) + } - function drawBackground() { + let point2 = { + x: viewPort.visibleArea.topLeft.x + imageWidth * 8, + y: viewPort.visibleArea.topLeft.y + } - if (INTENSIVE_LOG === true) { logger.write("[INFO] drawBackground -> Entering function."); } + backgroundLogoPoint2 = { + x: getDateFromPoint(point2, thisObject.container, timeLineCoordinateSystem).valueOf(), + y: getRateFromPoint(point2, thisObject.container, timeLineCoordinateSystem) + } - if (canDrawLogoA === false || canDrawLogoB === false || canDrawLogoExchange === false || canDrawLogoAA === false) { return; } + let currentCorner = { + x: getDateFromPoint(viewPort.visibleArea.topLeft, thisObject.container, timeLineCoordinateSystem).valueOf(), + y: getRateFromPoint(viewPort.visibleArea.topLeft, thisObject.container, timeLineCoordinateSystem) + } - let backgroundLogoPoint1; - let backgroundLogoPoint2; + currentCorner.x = Math.trunc(currentCorner.x / (backgroundLogoPoint2.x - backgroundLogoPoint1.x)) * (backgroundLogoPoint2.x - backgroundLogoPoint1.x) - let imageHeight = 42; - let imageWidth = 150; + let rowHight = (viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y) / 4.5 - let MAX_COLUMNS = 16; - let MAX_ROWS = 7; - let Y_TOP_MARGIN = 30; + imagePoint = timeLineCoordinateSystem.transformThisPoint(currentCorner) + imagePoint = transformThisPoint(imagePoint, thisObject.container) - let point1 = { - x: viewPort.visibleArea.topLeft.x, - y: viewPort.visibleArea.topLeft.y - }; + let offSet = 0 - backgroundLogoPoint1 = { - x: getDateFromPoint(point1, thisObject.container, timeLineCoordinateSystem).valueOf(), - y: getRateFromPoint(point1, thisObject.container, timeLineCoordinateSystem) - }; + for (let j = 0; j < MAX_ROWS; j++) { + if (offSet === -imageWidth * 8) { + offSet = -imageWidth * 4 - imageWidth + } else { + offSet = -imageWidth * 8 + } - let point2 = { - x: viewPort.visibleArea.topLeft.x + imageWidth * 8, - y: viewPort.visibleArea.topLeft.y - }; + for (let i = 0; i < MAX_COLUMNS; i = i + 4) { + let logo = logoA - backgroundLogoPoint2 = { - x: getDateFromPoint(point2, thisObject.container, timeLineCoordinateSystem).valueOf(), - y: getRateFromPoint(point2, thisObject.container, timeLineCoordinateSystem) - }; + browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight) + } + } - let currentCorner = { - x: getDateFromPoint(viewPort.visibleArea.topLeft, thisObject.container, timeLineCoordinateSystem).valueOf(), - y: getRateFromPoint(viewPort.visibleArea.topLeft, thisObject.container, timeLineCoordinateSystem) - }; + offSet = 0 - currentCorner.x = Math.trunc(currentCorner.x / (backgroundLogoPoint2.x - backgroundLogoPoint1.x)) * (backgroundLogoPoint2.x - backgroundLogoPoint1.x); + for (let j = 0; j < MAX_ROWS; j++) { + if (offSet === -imageWidth * 8) { + offSet = -imageWidth * 4 - imageWidth + } else { + offSet = -imageWidth * 8 + } - let rowHight = (viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y) / 4.5; + for (let i = 1; i < MAX_COLUMNS; i = i + 4) { + let logo = logoB - imagePoint = timeLineCoordinateSystem.transformThisPoint(currentCorner); - imagePoint = transformThisPoint(imagePoint, thisObject.container); + browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight) + } + } - let offSet = 0; + offSet = 0 + for (let j = 0; j < MAX_ROWS; j++) { + if (offSet === -imageWidth * 8) { + offSet = -imageWidth * 4 - imageWidth + } else { + offSet = -imageWidth * 8 + } - for (let j = 0; j < MAX_ROWS; j++) { + for (let i = 2; i < MAX_COLUMNS; i = i + 4) { + let logo = logoExchange - if (offSet === -imageWidth * 8) { + browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight) + } + } - offSet = -imageWidth * 4 - imageWidth; + offSet = 0 - } else { - offSet = -imageWidth * 8; - } + for (let j = 0; j < MAX_ROWS; j++) { + if (offSet === -imageWidth * 8) { + offSet = -imageWidth * 4 - imageWidth + } else { + offSet = -imageWidth * 8 + } - for (let i = 0; i < MAX_COLUMNS; i = i + 4) { + for (let i = 3; i < MAX_COLUMNS; i = i + 4) { + let logo = logoAA - let logo = logoA; - - browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight); - - } - } - - offSet = 0; - - for (let j = 0; j < MAX_ROWS; j++) { - - if (offSet === -imageWidth * 8) { - - offSet = -imageWidth * 4 - imageWidth; - - } else { - offSet = -imageWidth * 8; - } - - for (let i = 1; i < MAX_COLUMNS; i = i + 4) { - - let logo = logoB; - - browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight); - - } - } - - offSet = 0; - - for (let j = 0; j < MAX_ROWS; j++) { - - if (offSet === -imageWidth * 8) { - - offSet = -imageWidth * 4 - imageWidth; - - } else { - offSet = -imageWidth * 8; - } - - for (let i = 2; i < MAX_COLUMNS; i = i + 4) { - - let logo = logoExchange; - - browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight); - - } - } - - offSet = 0; - - for (let j = 0; j < MAX_ROWS; j++) { - - if (offSet === -imageWidth * 8) { - - offSet = -imageWidth * 4 - imageWidth; - - } else { - offSet = -imageWidth * 8; - } - - for (let i = 3; i < MAX_COLUMNS; i = i + 4) { - - let logo = logoAA; - - browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight); - - } - } + browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight) + } + } /* We will paint some transparent background here. */ - let opacity = "0.9"; + let opacity = '0.9' - let fromPoint = { - x: 0, - y: 0 - }; + let fromPoint = { + x: 0, + y: 0 + } - let toPoint = { - x: 0, - y: thisObject.container.frame.height - }; + let toPoint = { + x: 0, + y: thisObject.container.frame.height + } - fromPoint = transformThisPoint(fromPoint, thisObject.container); - toPoint = transformThisPoint(toPoint, thisObject.container); + fromPoint = transformThisPoint(fromPoint, thisObject.container) + toPoint = transformThisPoint(toPoint, thisObject.container) - browserCanvasContext.beginPath(); + browserCanvasContext.beginPath() - browserCanvasContext.rect(viewPort.visibleArea.topLeft.x, fromPoint.y, viewPort.visibleArea.topRight.x - viewPort.visibleArea.topLeft.x, toPoint.y - fromPoint.y); - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'; + browserCanvasContext.rect(viewPort.visibleArea.topLeft.x, fromPoint.y, viewPort.visibleArea.topRight.x - viewPort.visibleArea.topLeft.x, toPoint.y - fromPoint.y) + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')' - browserCanvasContext.closePath(); + browserCanvasContext.closePath() - browserCanvasContext.fill(); + browserCanvasContext.fill() + } - } + function moveViewPortToCurrentDatetime () { + if (INFO_LOG === true) { logger.write('[INFO] moveViewPortToCurrentDatetime -> Entering function.') } - function moveViewPortToCurrentDatetime() { - - if (INFO_LOG === true) { logger.write("[INFO] moveViewPortToCurrentDatetime -> Entering function."); } - - let targetPoint = { - x: datetime.valueOf(), - y: 0 // we wont touch the y axis here. - }; + let targetPoint = { + x: datetime.valueOf(), + y: 0 // we wont touch the y axis here. + } /* Lets put this point in the coordinate system of the viewPort */ - targetPoint = timeLineCoordinateSystem.transformThisPoint(targetPoint); - targetPoint = transformThisPoint(targetPoint, thisObject.container); + targetPoint = timeLineCoordinateSystem.transformThisPoint(targetPoint) + targetPoint = transformThisPoint(targetPoint, thisObject.container) /* Lets get the point on the viewPort coordinate system of the center of the visible screen */ - let center = { - x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2, - y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) / 2 - }; + let center = { + x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2, + y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) / 2 + } /* Lets calculate the displace vector, from the point we want at the center, to the current center. */ - let displaceVector = { - x: center.x - targetPoint.x, - y: 0 - }; + let displaceVector = { + x: center.x - targetPoint.x, + y: 0 + } - viewPort.displace(displaceVector); - } -} + viewPort.displace(displaceVector) + } + } diff --git a/TopSpace/CompanyLogo.js b/TopSpace/CompanyLogo.js index b29d93a43..2f981f540 100644 --- a/TopSpace/CompanyLogo.js +++ b/TopSpace/CompanyLogo.js @@ -1,84 +1,75 @@ - -function newCompanyLogo() { +  +function newCompanyLogo () { + var thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container - var container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 150 + thisObject.container.frame.height = TOP_SPACE_HEIGHT - thisObject.container.frame.width = 150; - thisObject.container.frame.height = TOP_SPACE_HEIGHT; + container.frame.position.x = 0 + container.frame.position.y = 0 - container.frame.position.x = 0; - container.frame.position.y = 0; + container.isDraggeable = false - container.isDraggeable = false; + let logo + let canDrawLogo = false - let logo; - let canDrawLogo = false; - - return thisObject; - - function initialize() { - - if (window.canvasApp.executingAt === 'Master App') { - currentLabel = ""; - return; - } - - logo = new Image(); - - logo.onload = onImageLoad; - - function onImageLoad() { - canDrawLogo = true; - } - - logo.src = window.canvasApp.urlPrefix + "Images/aa-logo-dark-8.png"; + return thisObject + function initialize () { + if (window.canvasApp.executingAt === 'Master App') { + currentLabel = '' + return } - function getContainer(point) { + logo = new Image() - let container; + logo.onload = onImageLoad + + function onImageLoad () { + canDrawLogo = true + } + + logo.src = window.canvasApp.urlPrefix + 'Images/aa-logo-dark-8.png' + } + + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } + return undefined + } + } + function draw () { + thisObject.container.frame.draw(false, false) + + if (canDrawLogo === false) { return } + + let imageHeight = 24 + let imageWidth = 120 + + let imagePoint = { + x: 10, + y: thisObject.container.frame.height / 2 - imageHeight / 2 } - function draw() { + imagePoint = thisObject.container.frame.frameThisPoint(imagePoint) - thisObject.container.frame.draw(false, false); - - if (canDrawLogo === false) { return;} - - let imageHeight = 24; - let imageWidth = 120; - - let imagePoint = { - x: 10, - y: thisObject.container.frame.height / 2 - imageHeight / 2 - }; - - imagePoint = thisObject.container.frame.frameThisPoint(imagePoint); - - browserCanvasContext.drawImage(logo, imagePoint.x, imagePoint.y, imageWidth, imageHeight); - } -} \ No newline at end of file + browserCanvasContext.drawImage(logo, imagePoint.x, imagePoint.y, imageWidth, imageHeight) + } +} diff --git a/TopSpace/CurrentBot.js b/TopSpace/CurrentBot.js index 99ba6f380..34bb64339 100644 --- a/TopSpace/CurrentBot.js +++ b/TopSpace/CurrentBot.js @@ -1,156 +1,137 @@ - -function newCurrentBot() { +  +function newCurrentBot () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 150 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 150; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize(); + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + const NOT_FOUND = '' - const NOT_FOUND = ""; + let sharedStatus - let sharedStatus; + return thisObject - return thisObject; + function initialize (pSharedStatus) { + sharedStatus = pSharedStatus - function initialize(pSharedStatus) { - - sharedStatus = pSharedStatus; - - if (window.USER_PROFILE.devTeams.length === 0) { - window.CURRENT_BOT_DISPLAY_NAME = NOT_FOUND; - } else { - - if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length === 0) { - window.CURRENT_BOT_DISPLAY_NAME = NOT_FOUND; - window.CURRENT_BOT_REPO = "NO REPO"; - window.CURRENT_BOT_CODE_NAME = ""; - } else { - window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName; - window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo; - window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName; - } - } - - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - sharedStatus.eventHandler.listenToEvent("devTeam Changed", onDevTeamChanged); - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + if (window.USER_PROFILE.devTeams.length === 0) { + window.CURRENT_BOT_DISPLAY_NAME = NOT_FOUND + } else { + if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length === 0) { + window.CURRENT_BOT_DISPLAY_NAME = NOT_FOUND + window.CURRENT_BOT_REPO = 'NO REPO' + window.CURRENT_BOT_CODE_NAME = '' + } else { + window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName + window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo + window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName + } } - function resize() { + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) + sharedStatus.eventHandler.listenToEvent('devTeam Changed', onDevTeamChanged) - container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 1; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } + function resize () { + container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 1 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } + + function onDevTeamChanged () { + if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length > 0) { + sharedStatus.currentUserBotIndex = 0 + window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName + window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo + window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName + + sharedStatus.eventHandler.raiseEvent('userBot Changed') + } else { + window.CURRENT_BOT_DISPLAY_NAME = NOT_FOUND } + } - function onDevTeamChanged() { + function onClick () { + let sessionToken = window.localStorage.getItem('sessionToken') - if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length > 0) { - - sharedStatus.currentUserBotIndex = 0; - window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName; - window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo; - window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName; - - sharedStatus.eventHandler.raiseEvent("userBot Changed"); - - } else { - - window.CURRENT_BOT_DISPLAY_NAME = NOT_FOUND; - - } - } - - function onClick() { - - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - if (sharedStatus.currentUserBotIndex + 1 === window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length) { - - sharedStatus.currentUserBotIndex = 0; - window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName; - window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo; - window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName; - - sharedStatus.eventHandler.raiseEvent("userBot Changed"); - return; - } - - if (sharedStatus.currentUserBotIndex + 1 < window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length) { - - sharedStatus.currentUserBotIndex++; - window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName; - window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo; - window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName; - - sharedStatus.eventHandler.raiseEvent("userBot Changed"); - return; - } + return } - function getContainer(point) { + if (sharedStatus.currentUserBotIndex + 1 === window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length) { + sharedStatus.currentUserBotIndex = 0 + window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName + window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo + window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName - let container; + sharedStatus.eventHandler.raiseEvent('userBot Changed') + return + } + + if (sharedStatus.currentUserBotIndex + 1 < window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length) { + sharedStatus.currentUserBotIndex++ + window.CURRENT_BOT_DISPLAY_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].displayName + window.CURRENT_BOT_REPO = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].repo + window.CURRENT_BOT_CODE_NAME = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].codeName + + sharedStatus.eventHandler.raiseEvent('userBot Changed') + return + } + } + + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } + } - function draw() { + function draw () { + let sessionToken = window.localStorage.getItem('sessionToken') - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - thisObject.container.frame.draw(false, false); - - let breakpointsHeight = 14; - let fontSize = 12; - let label = window.CURRENT_BOT_DISPLAY_NAME; - if (label === undefined) { label = "" }; - - let point = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, - y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight - }; - point = thisObject.container.frame.frameThisPoint(point); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, point.x, point.y); + return } -} \ No newline at end of file + + thisObject.container.frame.draw(false, false) + + let breakpointsHeight = 14 + let fontSize = 12 + let label = window.CURRENT_BOT_DISPLAY_NAME + if (label === undefined) { label = '' }; + + let point = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, + y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight + } + point = thisObject.container.frame.frameThisPoint(point) + + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, point.x, point.y) + } +} diff --git a/TopSpace/CurrentProcess.js b/TopSpace/CurrentProcess.js index 4e7d675ba..23ad46466 100644 --- a/TopSpace/CurrentProcess.js +++ b/TopSpace/CurrentProcess.js @@ -1,150 +1,130 @@ - -function newCurrentProcess() { +  +function newCurrentProcess () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 150 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 150; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize() + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + const NOT_FOUND = '' - const NOT_FOUND = ""; + let sharedStatus - let sharedStatus; + return thisObject - return thisObject; + function initialize (pSharedStatus) { + sharedStatus = pSharedStatus - function initialize(pSharedStatus) { - - sharedStatus = pSharedStatus; - - if (window.USER_PROFILE.devTeams.length === 0) { - window.CURRENT_PROCESS = NOT_FOUND; + if (window.USER_PROFILE.devTeams.length === 0) { + window.CURRENT_PROCESS = NOT_FOUND + } else { + if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length === 0) { + window.CURRENT_PROCESS = NOT_FOUND + } else { + if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length === 0) { + window.CURRENT_PROCESS = NOT_FOUND } else { - - if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length === 0) { - window.CURRENT_PROCESS = NOT_FOUND; - } else { - - if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length === 0) { - window.CURRENT_PROCESS = NOT_FOUND; - } else { - - window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name; - - } - } + window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name } - - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - sharedStatus.eventHandler.listenToEvent("userBot Changed", onUserBotChanged); - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + } } - function resize() { + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) + sharedStatus.eventHandler.listenToEvent('userBot Changed', onUserBotChanged) - container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 2; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } + function resize () { + container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 2 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } + + function onUserBotChanged () { + if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length > 0) { + if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length > 0) { + sharedStatus.currentProcessIndex = 0 + window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name + + return + } } - function onUserBotChanged() { + window.CURRENT_PROCESS = NOT_FOUND + } - if ( window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots.length > 0) { + function onClick () { + let sessionToken = window.localStorage.getItem('sessionToken') - if (window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length > 0) { - - sharedStatus.currentProcessIndex = 0; - window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name; - - return; - } - } - - window.CURRENT_PROCESS = NOT_FOUND; - } - - function onClick() { - - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - if (sharedStatus.currentProcessIndex + 1 === window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length) { - - sharedStatus.currentProcessIndex = 0; - window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name; - return; - } - - if (sharedStatus.currentProcessIndex + 1 < window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length) { - - sharedStatus.currentProcessIndex++; - window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name; - return; - } + return } - function getContainer(point) { + if (sharedStatus.currentProcessIndex + 1 === window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length) { + sharedStatus.currentProcessIndex = 0 + window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name + return + } - let container; + if (sharedStatus.currentProcessIndex + 1 < window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes.length) { + sharedStatus.currentProcessIndex++ + window.CURRENT_PROCESS = window.USER_PROFILE.devTeams[sharedStatus.currentDevTeamIndex].userBots[sharedStatus.currentUserBotIndex].processes[sharedStatus.currentProcessIndex].name + return + } + } + + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } + } - function draw() { + function draw () { + let sessionToken = window.localStorage.getItem('sessionToken') - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - thisObject.container.frame.draw(false, false); - - let breakpointsHeight = 14; - let fontSize = 12; - let label = window.CURRENT_PROCESS; - if (label === undefined) { label = "" }; - - let point = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, - y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight - }; - - point = thisObject.container.frame.frameThisPoint(point); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, point.x, point.y); + return } -} \ No newline at end of file + + thisObject.container.frame.draw(false, false) + + let breakpointsHeight = 14 + let fontSize = 12 + let label = window.CURRENT_PROCESS + if (label === undefined) { label = '' }; + + let point = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, + y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight + } + + point = thisObject.container.frame.frameThisPoint(point) + + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, point.x, point.y) + } +} diff --git a/TopSpace/CurrentStartMode.js b/TopSpace/CurrentStartMode.js index eaff70645..e0b75b3f8 100644 --- a/TopSpace/CurrentStartMode.js +++ b/TopSpace/CurrentStartMode.js @@ -1,122 +1,110 @@ - -function newCurrentStartMode() { +  +function newCurrentStartMode () { + var thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, // returns the inner most container that holds the point received by parameter. + initialize: initialize + } - var thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, // returns the inner most container that holds the point received by parameter. - initialize: initialize - }; + var container = newContainer() + container.initialize() + thisObject.container = container - var container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 150 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 150; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize(); + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + return thisObject - return thisObject; + function initialize () { + window.CURRENT_START_MODE = window.localStorage.getItem('currentStartMode') - function initialize() { - - window.CURRENT_START_MODE = window.localStorage.getItem("currentStartMode"); - - if (window.CURRENT_START_MODE === null) { - window.CURRENT_START_MODE = "Backtest"; - } - - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + if (window.CURRENT_START_MODE === null) { + window.CURRENT_START_MODE = 'Backtest' } - function resize() { + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 3; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } - } + function resize () { + container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 3 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } - function onClick() { + function onClick () { + let sessionToken = window.localStorage.getItem('sessionToken') - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - if (window.CURRENT_BOT_DISPLAY_NAME === "") { return; } - - switch (window.CURRENT_START_MODE) { - - case "Backtest": { - window.CURRENT_START_MODE = "Live"; - break; - } - case "Live": { - window.CURRENT_START_MODE = "Competition"; - break; - } - case "Competition": { - window.CURRENT_START_MODE = "Backtest"; - break; - } - } - + return } - function getContainer(point) { + if (window.CURRENT_BOT_DISPLAY_NAME === '') { return } - let container; + switch (window.CURRENT_START_MODE) { + + case 'Backtest': { + window.CURRENT_START_MODE = 'Live' + break + } + case 'Live': { + window.CURRENT_START_MODE = 'Competition' + break + } + case 'Competition': { + window.CURRENT_START_MODE = 'Backtest' + break + } + } + } + + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } + } - function draw() { + function draw () { + let sessionToken = window.localStorage.getItem('sessionToken') - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - if (window.CURRENT_BOT_DISPLAY_NAME === "") { return;} - - thisObject.container.frame.draw(false, false); - - let breakpointsHeight = 14; - let fontSize = 12; - let label = window.CURRENT_START_MODE + " Mode"; - if (label === "undefined Mode") { label = "" }; - - let point = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, - y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight - }; - - point = thisObject.container.frame.frameThisPoint(point); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, point.x, point.y); + return } -} \ No newline at end of file + + if (window.CURRENT_BOT_DISPLAY_NAME === '') { return } + + thisObject.container.frame.draw(false, false) + + let breakpointsHeight = 14 + let fontSize = 12 + let label = window.CURRENT_START_MODE + ' Mode' + if (label === 'undefined Mode') { label = '' }; + + let point = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, + y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight + } + + point = thisObject.container.frame.frameThisPoint(point) + + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, point.x, point.y) + } +} diff --git a/TopSpace/DevTeam.js b/TopSpace/DevTeam.js index 1ca8ce15a..d6ae96865 100644 --- a/TopSpace/DevTeam.js +++ b/TopSpace/DevTeam.js @@ -1,140 +1,126 @@ - -function newDevTeam() { +  +function newDevTeam () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 150 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 150; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + resize() - resize(); + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + const NOT_FOUND = 'Team NOT FOUND' - const NOT_FOUND = "Team NOT FOUND"; + let sharedStatus + let label = '' - let sharedStatus; - let label = "" + return thisObject - return thisObject; + function initialize (pSharedStatus) { + let sessionToken = window.localStorage.getItem('sessionToken') - function initialize(pSharedStatus) { - - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - sharedStatus = pSharedStatus; - - let storedTeams = window.localStorage.getItem('userTeams'); - - if (storedTeams === null || storedTeams === "[]" || storedTeams === "") { - window.TEAMS = ""; - window.DEV_TEAM = ""; - label = NOT_FOUND; - } else { - storedTeams = JSON.parse(storedTeams) - window.TEAMS = storedTeams; - window.DEV_TEAM = storedTeams[sharedStatus.currentDevTeamIndex].slug; - label = storedTeams[sharedStatus.currentDevTeamIndex].name; - sharedStatus.eventHandler.raiseEvent("devTeam Changed"); - } - - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); - - window.canvasApp.eventHandler.listenToEvent("Browser Resized", resize); + return } - function resize() { + sharedStatus = pSharedStatus - container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 0; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + let storedTeams = window.localStorage.getItem('userTeams') + if (storedTeams === null || storedTeams === '[]' || storedTeams === '') { + window.TEAMS = '' + window.DEV_TEAM = '' + label = NOT_FOUND + } else { + storedTeams = JSON.parse(storedTeams) + window.TEAMS = storedTeams + window.DEV_TEAM = storedTeams[sharedStatus.currentDevTeamIndex].slug + label = storedTeams[sharedStatus.currentDevTeamIndex].name + sharedStatus.eventHandler.raiseEvent('devTeam Changed') } - function onClick() { + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - let sessionToken = window.localStorage.getItem('sessionToken'); + window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize) + } - if (sessionToken === null || sessionToken === "") { + function resize () { + container.frame.position.x = viewPort.visibleArea.topLeft.x + thisObject.container.frame.width * 0 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y + } + + function onClick () { + let sessionToken = window.localStorage.getItem('sessionToken') + + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - if (sharedStatus.currentDevTeamIndex + 1 === window.TEAMS.length) { - - sharedStatus.currentDevTeamIndex = 0; - window.DEV_TEAM = window.TEAMS[sharedStatus.currentDevTeamIndex].slug; - label = window.TEAMS[sharedStatus.currentDevTeamIndex].name; - sharedStatus.eventHandler.raiseEvent("devTeam Changed"); - return; - } - - if (sharedStatus.currentDevTeamIndex + 1 < window.TEAMS.length) { - - sharedStatus.currentDevTeamIndex++; - window.DEV_TEAM = window.TEAMS[sharedStatus.currentDevTeamIndex].slug; - label = window.TEAMS[sharedStatus.currentDevTeamIndex].name; - sharedStatus.eventHandler.raiseEvent("devTeam Changed"); - return; - } - + return } - function getContainer(point) { + if (sharedStatus.currentDevTeamIndex + 1 === window.TEAMS.length) { + sharedStatus.currentDevTeamIndex = 0 + window.DEV_TEAM = window.TEAMS[sharedStatus.currentDevTeamIndex].slug + label = window.TEAMS[sharedStatus.currentDevTeamIndex].name + sharedStatus.eventHandler.raiseEvent('devTeam Changed') + return + } - let container; + if (sharedStatus.currentDevTeamIndex + 1 < window.TEAMS.length) { + sharedStatus.currentDevTeamIndex++ + window.DEV_TEAM = window.TEAMS[sharedStatus.currentDevTeamIndex].slug + label = window.TEAMS[sharedStatus.currentDevTeamIndex].name + sharedStatus.eventHandler.raiseEvent('devTeam Changed') + return + } + } + + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } - + return undefined } + } - function draw() { + function draw () { + let sessionToken = window.localStorage.getItem('sessionToken') - let sessionToken = window.localStorage.getItem('sessionToken'); - - if (sessionToken === null || sessionToken === "") { + if (sessionToken === null || sessionToken === '') { /* not logged in */ - return; - } - - thisObject.container.frame.draw(false, false); - - let breakpointsHeight = 14; - let fontSize = 12; - - let point = { - x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, - y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight - }; - - point = thisObject.container.frame.frameThisPoint(point); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, point.x, point.y); + return } + + thisObject.container.frame.draw(false, false) + + let breakpointsHeight = 14 + let fontSize = 12 + + let point = { + x: thisObject.container.frame.width / 2 - label.length / 2 * fontSize / 3, + y: thisObject.container.frame.height / 2 + fontSize / 2 + breakpointsHeight + } + + point = thisObject.container.frame.frameThisPoint(point) + + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, point.x, point.y) + } } diff --git a/TopSpace/EndUser.js b/TopSpace/EndUser.js index b71305b67..2f70223ce 100644 --- a/TopSpace/EndUser.js +++ b/TopSpace/EndUser.js @@ -1,96 +1,84 @@ - -function newEndUser() { +  +function newEndUser () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 200 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 200; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width * 5 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y - container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width * 5; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + container.isDraggeable = false - container.isDraggeable = false; + return thisObject - return thisObject; - - function initialize() { - - let storedUser = window.localStorage.getItem('loggedInUser'); - - if (storedUser === null || storedUser === "") { + function initialize () { + let storedUser = window.localStorage.getItem('loggedInUser') + if (storedUser === null || storedUser === '') { // User is currently not logged in. - window.USER_LOGGED_IN = ""; - return; - } + window.USER_LOGGED_IN = '' + return + } - let loggedInUser = JSON.parse(storedUser); + let loggedInUser = JSON.parse(storedUser) - window.USER_LOGGED_IN = loggedInUser.alias; + window.USER_LOGGED_IN = loggedInUser.alias /* Here we will rearrange the storage permissions array into a map, so that it can be easily consumed when needed. */ - let permissionsMap = new Map; + let permissionsMap = new Map() - for (i = 0; i < window.USER_PROFILE.storagePermissions.length; i++) { - - let permission = window.USER_PROFILE.storagePermissions[i]; - - permissionsMap.set(permission[0], permission[1]); - - } - - window.USER_PROFILE.storagePermissions = permissionsMap; + for (i = 0; i < window.USER_PROFILE.storagePermissions.length; i++) { + let permission = window.USER_PROFILE.storagePermissions[i] + permissionsMap.set(permission[0], permission[1]) } - function getContainer(point) { + window.USER_PROFILE.storagePermissions = permissionsMap + } - let container; + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } + return undefined + } + } + function draw () { + return // nothing to show + + thisObject.container.frame.draw(false, false) + + let fontSize = 12 + let label = window.USER_LOGGED_IN + if (label === undefined) { label = '' }; + + let point = { + x: thisObject.container.frame.width * 1 / 3, + y: (thisObject.container.frame.height / 2) + 4 } - function draw() { + point = thisObject.container.frame.frameThisPoint(point) - return; // nothing to show - - thisObject.container.frame.draw(false, false); - - let fontSize = 12; - let label = window.USER_LOGGED_IN; - if (label === undefined) { label = "" }; - - let point = { - x: thisObject.container.frame.width * 1 / 3, - y: (thisObject.container.frame.height / 2) + 4 - }; - - point = thisObject.container.frame.frameThisPoint(point); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, point.x, point.y); - } -} \ No newline at end of file + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, point.x, point.y) + } +} diff --git a/TopSpace/Login.js b/TopSpace/Login.js index a94fd7871..d4753ecc1 100644 --- a/TopSpace/Login.js +++ b/TopSpace/Login.js @@ -1,62 +1,58 @@ - -function newLogin() { +  +function newLogin () { + let thisObject = { + container: undefined, + draw: draw, + getContainer: getContainer, + initialize: initialize + } - let thisObject = { - container: undefined, - draw: draw, - getContainer: getContainer, - initialize: initialize - }; + let container = newContainer() + container.initialize() + thisObject.container = container - let container = newContainer(); - container.initialize(); - thisObject.container = container; + thisObject.container.frame.width = 200 + thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT - thisObject.container.frame.width = 200; - thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT; + container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width * 1 + container.frame.position.y = viewPort.visibleArea.bottomLeft.y - container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width * 1; - container.frame.position.y = viewPort.visibleArea.bottomLeft.y; + container.isDraggeable = false + container.isClickeable = true - container.isDraggeable = false; - container.isClickeable = true; + let currentLabel - let currentLabel; + let userAuthorization - let userAuthorization; + return thisObject - return thisObject; - - function initialize(callBackFunction) { - - - const accessToken = window.localStorage.getItem("access_token"); - let user = window.localStorage.getItem("user"); - - if (user === null) { + function initialize (callBackFunction) { + const accessToken = window.localStorage.getItem('access_token') + let user = window.localStorage.getItem('user') + if (user === null) { // if there is no user that means that we are logged off, which means it is time to clean the local storage of things from the last log in. - window.localStorage.removeItem("loggedInUser"); - window.localStorage.removeItem('sessionToken'); - return; - } + window.localStorage.removeItem('loggedInUser') + window.localStorage.removeItem('sessionToken') + return + } - user = JSON.parse(user); + user = JSON.parse(user) - const authId = user.authId; + const authId = user.authId - let sessionToken; + let sessionToken - const apolloClient = new Apollo.lib.ApolloClient({ - networkInterface: Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl, - transportBatching: true, - }), - connectToDevTools: true, - }) + const apolloClient = new Apollo.lib.ApolloClient({ + networkInterface: Apollo.lib.createNetworkInterface({ + uri: window.canvasApp.graphQL.masterAppApiUrl, + transportBatching: true + }), + connectToDevTools: true + }) - const QUERY = Apollo.gql` + const QUERY = Apollo.gql` query($authId: String){ users_UserByAuthId (authId: $authId){ id @@ -80,46 +76,46 @@ function newLogin() { } } ` - const getUser = () => { - return new Promise((resolve, reject) => { - apolloClient.query({ - query: QUERY, - variables: { - authId: authId - } - }) + const getUser = () => { + return new Promise((resolve, reject) => { + apolloClient.query({ + query: QUERY, + variables: { + authId: authId + } + }) .then(response => { - sessionToken = response.data.users_UserByAuthId.sessionToken; - - window.localStorage.setItem('loggedInUser', JSON.stringify(response.data.users_UserByAuthId)); - resolve({ user: response.data.users_UserByAuthId}) + sessionToken = response.data.users_UserByAuthId.sessionToken + + window.localStorage.setItem('loggedInUser', JSON.stringify(response.data.users_UserByAuthId)) + resolve({ user: response.data.users_UserByAuthId}) }) .catch(error => { - console.log("apolloClient error getting user query", error) - reject(error) - }); - }); - } + console.log('apolloClient error getting user query', error) + reject(error) + }) + }) + } - const networkInterfaceTeams = Apollo.lib.createNetworkInterface({ - uri: window.canvasApp.graphQL.masterAppApiUrl - }); + const networkInterfaceTeams = Apollo.lib.createNetworkInterface({ + uri: window.canvasApp.graphQL.masterAppApiUrl + }) - networkInterfaceTeams.use([{ - applyMiddleware(req, next) { - req.options.headers = { - authorization: `Bearer ${accessToken}` - }; - next(); - } - }]); + networkInterfaceTeams.use([{ + applyMiddleware (req, next) { + req.options.headers = { + authorization: `Bearer ${accessToken}` + } + next() + } + }]) - const apolloClientTeams = new Apollo.lib.ApolloClient({ - networkInterface: networkInterfaceTeams, - connectToDevTools: true, - }); + const apolloClientTeams = new Apollo.lib.ApolloClient({ + networkInterface: networkInterfaceTeams, + connectToDevTools: true + }) - const TEAM_BY_OWNER_QUERY = Apollo.gql` + const TEAM_BY_OWNER_QUERY = Apollo.gql` query teamsByOwnerQuery { teams_TeamsByOwner { id @@ -153,113 +149,100 @@ function newLogin() { } ` - const getTeamByOwner = () => { - return new Promise((resolve, reject) => { - apolloClientTeams.query({ - query: TEAM_BY_OWNER_QUERY - }) + const getTeamByOwner = () => { + return new Promise((resolve, reject) => { + apolloClientTeams.query({ + query: TEAM_BY_OWNER_QUERY + }) .then(response => { - window.localStorage.setItem('userTeams', JSON.stringify(response.data.teams_TeamsByOwner)); - resolve({ teams: response.data.teams_TeamsByOwner}) + window.localStorage.setItem('userTeams', JSON.stringify(response.data.teams_TeamsByOwner)) + resolve({ teams: response.data.teams_TeamsByOwner}) }) .catch(error => { - console.log("apolloClient error getting user teams", error) - reject (error) - }); + console.log('apolloClient error getting user teams', error) + reject(error) }) - } + }) + } // To avoid race conditions, add asynchronous fetches to array - let fetchDataPromises = []; + let fetchDataPromises = [] - fetchDataPromises.push(getUser(), getTeamByOwner()); + fetchDataPromises.push(getUser(), getTeamByOwner()) // When all asynchronous fetches resolve, authenticate user or throw error. - Promise.all(fetchDataPromises).then(result => { - + Promise.all(fetchDataPromises).then(result => { /* this is the time to authenticate the user at AAWeb */ - authenticateUser(); + authenticateUser() + }, err => { + console.error('fetchData error', err) + }) - }, err => { - console.error("fetchData error", err) - }); + thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick) - thisObject.container.eventHandler.listenToEvent("onMouseClick", onClick); + function authenticateUser () { + if (sessionToken === undefined) { sessionToken = '' } - function authenticateUser() { + let path = window.canvasApp.urlPrefix + 'AABrowserAPI/authenticateUser/' + sessionToken - if (sessionToken === undefined) { sessionToken = "" } + callServer(undefined, path, onServerReponded) - let path = window.canvasApp.urlPrefix + "AABrowserAPI/authenticateUser/" + sessionToken; + function onServerReponded (pResponseFromServer) { + let responseFromServer = JSON.parse(pResponseFromServer) - callServer(undefined, path, onServerReponded); + err = responseFromServer.err - function onServerReponded(pResponseFromServer) { - - let responseFromServer = JSON.parse(pResponseFromServer); - - err = responseFromServer.err; - - if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { - - console.log("Please make sure you create a new team!"); - return; - - } - - window.USER_PROFILE = responseFromServer.userProfile; - window.localStorage.setItem('sessionToken', sessionToken); - - currentLabel = "Logged In" - callBackFunction(); - } + if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) { + console.log('Please make sure you create a new team!') + return } + + window.USER_PROFILE = responseFromServer.userProfile + window.localStorage.setItem('sessionToken', sessionToken) + + currentLabel = 'Logged In' + callBackFunction() + } } + } + function onClick () { - function onClick() { - - } + } - function getContainer(point) { - - let container; + function getContainer (point) { + let container /* First we check if this point is inside this object UI. */ - if (thisObject.container.frame.isThisPointHere(point, true) === true) { - - return this.container; - - } else { - + if (thisObject.container.frame.isThisPointHere(point, true) === true) { + return this.container + } else { /* This point does not belong to this space. */ - return undefined; - } + return undefined + } + } + function draw () { + return // nothing to show. + + thisObject.container.frame.draw(false, false) + + let fontSize = 12 + let label = currentLabel + if (label === undefined) { label = '' }; + + let point = { + x: thisObject.container.frame.width * 1 / 3, + y: (thisObject.container.frame.height / 2) + 4 } - function draw() { + point = thisObject.container.frame.frameThisPoint(point) - return; // nothing to show. - - thisObject.container.frame.draw(false, false); - - let fontSize = 12; - let label = currentLabel; - if (label === undefined) { label = "" }; - - let point = { - x: thisObject.container.frame.width * 1 / 3, - y: (thisObject.container.frame.height / 2) + 4 - }; - - point = thisObject.container.frame.frameThisPoint(point); - - browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY; - browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'; - browserCanvasContext.fillText(label, point.x, point.y); - } + browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY + browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)' + browserCanvasContext.fillText(label, point.x, point.y) + } } diff --git a/Utilities.js b/Utilities.js index d8f5fe355..ecf946f0b 100644 --- a/Utilities.js +++ b/Utilities.js @@ -1,141 +1,128 @@ - - -function transformThisPoint(point, container) { +function transformThisPoint (point, container) { /* We make the point relative to the current frame */ - point = container.frame.frameThisPoint(point); + point = container.frame.frameThisPoint(point) /* We add the possible displacement */ - point = container.displacement.displaceThisPoint(point); + point = container.displacement.displaceThisPoint(point) /* We viewport Transformation. */ - point = viewPort.zoomThisPoint(point); + point = viewPort.zoomThisPoint(point) - return point; + return point } -function unTransformThisPoint(point, container) { +function unTransformThisPoint (point, container) { + point = viewPort.unzoomThisPoint(point) + point = container.displacement.undisplaceThisPoint(point) + point = container.frame.unframeThisPoint(point) - point = viewPort.unzoomThisPoint(point); - point = container.displacement.undisplaceThisPoint(point); - point = container.frame.unframeThisPoint(point); - - return point; + return point } -function nextPorwerOf10(number) { - - for (let i = -10; i <= 10; i++) { - if (number < Math.pow(10, i)) { - return Math.pow(10, i); - } +function nextPorwerOf10 (number) { + for (let i = -10; i <= 10; i++) { + if (number < Math.pow(10, i)) { + return Math.pow(10, i) } + } } -function pad(str, max) { - str = str.toString(); - return str.length < max ? pad("0" + str, max) : str; +function pad (str, max) { + str = str.toString() + return str.length < max ? pad('0' + str, max) : str } -function getDateFromPoint(point, container, timeLineCoordinateSystem) { +function getDateFromPoint (point, container, timeLineCoordinateSystem) { + point = unTransformThisPoint(point, container) + point = timeLineCoordinateSystem.unInverseTransform(point, container.frame.height) - point = unTransformThisPoint(point, container); - point = timeLineCoordinateSystem.unInverseTransform(point, container.frame.height); + let date = new Date(point.x) - let date = new Date(point.x); - - return date; + return date } -function getRateFromPoint(point, container, timeLineCoordinateSystem) { +function getRateFromPoint (point, container, timeLineCoordinateSystem) { + point = unTransformThisPoint(point, container) + point = timeLineCoordinateSystem.unInverseTransform(point, container.frame.height) - point = unTransformThisPoint(point, container); - point = timeLineCoordinateSystem.unInverseTransform(point, container.frame.height); - - return point.y; + return point.y } -function getMilisecondsFromPoint(point, container, timeLineCoordinateSystem) { +function getMilisecondsFromPoint (point, container, timeLineCoordinateSystem) { + point = unTransformThisPoint(point, container) + point = timeLineCoordinateSystem.unInverseTransform(point, container.frame.height) - point = unTransformThisPoint(point, container); - point = timeLineCoordinateSystem.unInverseTransform(point, container.frame.height); - - return point.x; + return point.x } -function saveUserPosition(container, timeLineCoordinateSystem) { +function saveUserPosition (container, timeLineCoordinateSystem) { + let centerPoint = { + x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.topLeft.x) / 2, + y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y) / 2 + } - let centerPoint = { - x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.topLeft.x) / 2, - y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y) / 2 - }; + let userPosition = { + date: getDateFromPoint(centerPoint, container, timeLineCoordinateSystem), + rate: getRateFromPoint(centerPoint, container, timeLineCoordinateSystem), + market: DEFAULT_MARKET, + zoom: viewPort.zoomTargetLevel + } - let userPosition = { - date: getDateFromPoint(centerPoint, container, timeLineCoordinateSystem), - rate: getRateFromPoint(centerPoint, container, timeLineCoordinateSystem), - market: DEFAULT_MARKET, - zoom: viewPort.zoomTargetLevel - }; - - window.localStorage.setItem('userPosition', JSON.stringify(userPosition)); + window.localStorage.setItem('userPosition', JSON.stringify(userPosition)) } -function moveToUserPosition(container, timeLineCoordinateSystem) { +function moveToUserPosition (container, timeLineCoordinateSystem) { + let savedPosition = window.localStorage.getItem('userPosition') + let userPosition - let savedPosition = window.localStorage.getItem('userPosition'); - let userPosition; - - if (savedPosition === null) { - - userPosition = { - date: (new Date()).toString(), - rate: timeLineCoordinateSystem.max.y / 2, - market: DEFAULT_MARKET, - zoom: INITIAL_ZOOM_LEVEL - }; - - } else { - - userPosition = JSON.parse(savedPosition); + if (savedPosition === null) { + userPosition = { + date: (new Date()).toString(), + rate: timeLineCoordinateSystem.max.y / 2, + market: DEFAULT_MARKET, + zoom: INITIAL_ZOOM_LEVEL } + } else { + userPosition = JSON.parse(savedPosition) + } - let centerPoint = { - x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.topLeft.x) / 2, - y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y) / 2 - }; + let centerPoint = { + x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.topLeft.x) / 2, + y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y) / 2 + } - viewPort.newZoomLevel(userPosition.zoom); - INITIAL_TIME_PERIOD = recalculatePeriod(userPosition.zoom); - INITIAL_DATE = new Date (userPosition.date); + viewPort.newZoomLevel(userPosition.zoom) + INITIAL_TIME_PERIOD = recalculatePeriod(userPosition.zoom) + INITIAL_DATE = new Date(userPosition.date) - let targetPoint = { - x: (new Date(userPosition.date)).valueOf(), - y: userPosition.rate - }; + let targetPoint = { + x: (new Date(userPosition.date)).valueOf(), + y: userPosition.rate + } /* Put this point in the coordinate system of the viewPort */ - targetPoint = timeLineCoordinateSystem.transformThisPoint(targetPoint); - targetPoint = transformThisPoint(targetPoint, container); + targetPoint = timeLineCoordinateSystem.transformThisPoint(targetPoint) + targetPoint = transformThisPoint(targetPoint, container) /* Lets calculate the displace vector, from the point we want at the center, to the current center. */ - let displaceVector = { - x: centerPoint.x - targetPoint.x, - y: centerPoint.y - targetPoint.y - }; + let displaceVector = { + x: centerPoint.x - targetPoint.x, + y: centerPoint.y - targetPoint.y + } - viewPort.displace(displaceVector); + viewPort.displace(displaceVector) } -function removeTime(datetime) { +function removeTime (datetime) { + if (datetime === undefined) { return } - if (datetime === undefined) { return;} + let dateOnly = new Date(Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS) * ONE_DAY_IN_MILISECONDS) - let dateOnly = new Date(Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS) * ONE_DAY_IN_MILISECONDS); - - return dateOnly; -} \ No newline at end of file + return dateOnly +} diff --git a/ViewPort.js b/ViewPort.js index 6213c15b1..cdebcd76f 100644 --- a/ViewPort.js +++ b/ViewPort.js @@ -1,100 +1,95 @@ - -function newViewPort() { +  +function newViewPort () { + const CONSOLE_LOG = true - const CONSOLE_LOG = true; + let ANIMATION_INCREMENT = 0.25 + const TOP_MARGIN = 15 + TOP_SPACE_HEIGHT + const BOTTOM_MARGIN = 15 + BOTTOM_SPACE_HEIGHT + const LEFT_MARGIN = 50 + const RIGHT_MARGIN = 50 + const MIN_ZOOM_LEVEL = -28.25 - let ANIMATION_INCREMENT = 0.25; - const TOP_MARGIN = 15 + TOP_SPACE_HEIGHT; - const BOTTOM_MARGIN = 15 + BOTTOM_SPACE_HEIGHT; - const LEFT_MARGIN = 50; - const RIGHT_MARGIN = 50; - const MIN_ZOOM_LEVEL = -28.25 + let thisObject = { + visibleArea: undefined, + eventHandler: undefined, + zoomTargetLevel: undefined, + zoomLevel: undefined, + mousePosition: undefined, + newZoomLevel: newZoomLevel, + applyZoom: applyZoom, + isMinZoom: isMinZoom, + zoomFontSize: zoomFontSize, + zoomThisPoint: zoomThisPoint, + unzoomThisPoint: unzoomThisPoint, + isThisPointVisible: isThisPointVisible, + fitIntoVisibleArea: fitIntoVisibleArea, + displace: displace, + displaceTarget: displaceTarget, + animate: animate, + draw: draw, + raiseEvents: raiseEvents, + initialize: initialize + } - let thisObject = { - visibleArea: undefined, - eventHandler: undefined, - zoomTargetLevel:undefined, - zoomLevel: undefined, - mousePosition: undefined, - newZoomLevel: newZoomLevel, - applyZoom: applyZoom, - isMinZoom: isMinZoom, - zoomFontSize: zoomFontSize, - zoomThisPoint: zoomThisPoint, - unzoomThisPoint: unzoomThisPoint, - isThisPointVisible: isThisPointVisible, - fitIntoVisibleArea: fitIntoVisibleArea, - displace: displace, - displaceTarget: displaceTarget, - animate: animate, - draw: draw, - raiseEvents: raiseEvents, - initialize: initialize - }; + let increment = 0.035 - let increment = 0.035; + var offset = { + x: 0, + y: 0 + } - var offset = { - x: 0, - y: 0 - }; + var targetOffset = { + x: 0, + y: 0 + } - var targetOffset = { - x: 0, - y: 0 - }; + let offsetIncrement = { + x: 0, + y: 0 + } - let offsetIncrement = { - x: 0, - y: 0 - }; + thisObject.mousePosition = { + x: 0, + y: 0 + } - thisObject.mousePosition = { - x: 0, - y: 0 - }; + thisObject.eventHandler = newEventHandler() - thisObject.eventHandler = newEventHandler(); + return thisObject - return thisObject; + function initialize () { + thisObject.visibleArea = { + topLeft: { x: LEFT_MARGIN, y: TOP_MARGIN }, + topRight: { x: browserCanvas.width - RIGHT_MARGIN, y: TOP_MARGIN }, + bottomRight: { x: browserCanvas.width - RIGHT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN}, + bottomLeft: { x: LEFT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN} + } + } - function initialize() { + function raiseEvents () { + let event = { + newOffset: offset + } - thisObject.visibleArea = { - topLeft: { x: LEFT_MARGIN, y: TOP_MARGIN }, - topRight: { x: browserCanvas.width - RIGHT_MARGIN , y: TOP_MARGIN }, - bottomRight: { x: browserCanvas.width - RIGHT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN}, - bottomLeft: { x: LEFT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN} - }; - } + thisObject.eventHandler.raiseEvent('Offset Changed', event) + } - function raiseEvents() { + function animate () { + if (thisObject.zoomLevel < thisObject.zoomTargetLevel) { + if (thisObject.zoomTargetLevel - thisObject.zoomLevel < ANIMATION_INCREMENT) { + ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) + } + thisObject.zoomLevel = thisObject.zoomLevel + ANIMATION_INCREMENT + changeZoom(thisObject.zoomLevel - ANIMATION_INCREMENT, thisObject.zoomLevel) + } - let event = { - newOffset: offset - }; - - thisObject.eventHandler.raiseEvent("Offset Changed", event); - - } - - function animate() { - - if (thisObject.zoomLevel < thisObject.zoomTargetLevel) { - if (thisObject.zoomTargetLevel - thisObject.zoomLevel < ANIMATION_INCREMENT) { - ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel); - } - thisObject.zoomLevel = thisObject.zoomLevel + ANIMATION_INCREMENT; - changeZoom(thisObject.zoomLevel - ANIMATION_INCREMENT, thisObject.zoomLevel); - } - - if (thisObject.zoomLevel > thisObject.zoomTargetLevel) { - if (thisObject.zoomLevel - thisObject.zoomTargetLevel < ANIMATION_INCREMENT) { - ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel); - } - thisObject.zoomLevel = thisObject.zoomLevel - ANIMATION_INCREMENT; - changeZoom(thisObject.zoomLevel + ANIMATION_INCREMENT, thisObject.zoomLevel); - } + if (thisObject.zoomLevel > thisObject.zoomTargetLevel) { + if (thisObject.zoomLevel - thisObject.zoomTargetLevel < ANIMATION_INCREMENT) { + ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) + } + thisObject.zoomLevel = thisObject.zoomLevel - ANIMATION_INCREMENT + changeZoom(thisObject.zoomLevel + ANIMATION_INCREMENT, thisObject.zoomLevel) + } /* if (offsetIncrement.x !== 0) { @@ -105,344 +100,290 @@ function newViewPort() { offsetIncrement.x = 0; } } -*/ +*/ - if (offsetIncrement.y !== 0) { + if (offsetIncrement.y !== 0) { + if (Math.trunc(Math.abs(targetOffset.y - offset.y) * 1000) >= Math.trunc(Math.abs(offsetIncrement.y) * 1000)) { + offset.y = offset.y + offsetIncrement.y - if (Math.trunc(Math.abs(targetOffset.y - offset.y) * 1000) >= Math.trunc(Math.abs(offsetIncrement.y) * 1000)) { - offset.y = offset.y + offsetIncrement.y; + // console.log("offset.y changed to " + offset.y) + } else { + offsetIncrement.y = 0 + } + } + } - //console.log("offset.y changed to " + offset.y) + function displace (displaceVector) { + offset.x = offset.x + displaceVector.x + offset.y = offset.y + displaceVector.y - } else { - offsetIncrement.y = 0; - } - } + let event = { + newOffset: offset + } - - } + thisObject.eventHandler.raiseEvent('Offset Changed', event) - function displace(displaceVector) { + // console.log("displace produced new Offset x = " + offset.x + " y = " + offset.y); + } - offset.x = offset.x + displaceVector.x; - offset.y = offset.y + displaceVector.y; + function displaceTarget (displaceVector) { + targetOffset.x = targetOffset.x + displaceVector.x + targetOffset.y = targetOffset.y + displaceVector.y - let event = { - newOffset: offset - }; + offsetIncrement = { + x: (targetOffset.x - offset.x) / 10, + y: (targetOffset.y - offset.y) / 10 + } - thisObject.eventHandler.raiseEvent("Offset Changed", event); + // console.log("displaceTarget x = " + targetOffset.x + " y = " + targetOffset.y); + } - //console.log("displace produced new Offset x = " + offset.x + " y = " + offset.y); + function newZoomLevel (level) { + thisObject.zoomTargetLevel = level + thisObject.zoomLevel = level - } + ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) / 3 - function displaceTarget(displaceVector) { + let event = { + newLevel: thisObject.zoomTargetLevel, + newOffset: offset, + type: undefined + } + thisObject.eventHandler.raiseEvent('Zoom Changed', event) - targetOffset.x = targetOffset.x + displaceVector.x; - targetOffset.y = targetOffset.y + displaceVector.y; + return true + } - - offsetIncrement = { - x: (targetOffset.x - offset.x) / 10, - y: (targetOffset.y - offset.y) / 10 - }; - - //console.log("displaceTarget x = " + targetOffset.x + " y = " + targetOffset.y); - - } - - function newZoomLevel(level) { - - thisObject.zoomTargetLevel = level; - thisObject.zoomLevel = level; - - ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) / 3; - - let event = { - newLevel: thisObject.zoomTargetLevel, - newOffset: offset, - type: undefined - }; - - thisObject.eventHandler.raiseEvent("Zoom Changed", event); - - return true; - } - - function isMinZoom() { + function isMinZoom () { /* returns true is we are currently at the min zoom level. */ - if (thisObject.zoomTargetLevel === MIN_ZOOM_LEVEL) { return true; } else { return false;} + if (thisObject.zoomTargetLevel === MIN_ZOOM_LEVEL) { return true } else { return false } + } - } + function applyZoom (amount) { + // console.log("applyZoom amount: " + amount); - function applyZoom(amount) { + if (amount > 0) { + if (thisObject.zoomTargetLevel > -5) { + amount = amount * 2 + } - //console.log("applyZoom amount: " + amount); - - if (amount > 0) { - - - if (thisObject.zoomTargetLevel > -5) { - amount = amount * 2; - } - - if (thisObject.zoomTargetLevel > 10) { - amount = amount * 3; - } - - if (thisObject.zoomTargetLevel > 15) { - amount = amount * 4; - } - } - - if (amount < 0) { - - if (thisObject.zoomTargetLevel > -4) { - amount = amount * 2; - } - - if (thisObject.zoomTargetLevel > 13) { - amount = amount * 3; - } - - if (thisObject.zoomTargetLevel > 19) { - amount = amount * 4; - } - } - - if (thisObject.zoomTargetLevel + amount > 1000) { - return false; - } - - if (thisObject.zoomTargetLevel <= -27 && amount < 0) { - amount = amount / 4; - } - - if (thisObject.zoomTargetLevel < -27 && amount > 0) { - amount = amount / 4; - } - - if (thisObject.zoomTargetLevel + amount < MIN_ZOOM_LEVEL) { - return false; - } - - thisObject.zoomTargetLevel = thisObject.zoomTargetLevel + amount; - - ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) / 3; - - let event = { - newLevel: thisObject.zoomTargetLevel, - newOffset: offset, - type: undefined - }; - - if (amount > 0) { - event.type = "Zoom In"; - } else { - event.type = "Zoom Out"; - } - - thisObject.eventHandler.raiseEvent("Zoom Changed", event); - - return true; - } - - - function changeZoom(oldLevel, newLevel) { - - let mouseNoZoom = unzoomThisPoint(thisObject.mousePosition, oldLevel); - let newMouse = zoomThisPoint(mouseNoZoom, newLevel); - - offset.x = offset.x - newMouse.x + thisObject.mousePosition.x; - offset.y = offset.y - newMouse.y + thisObject.mousePosition.y; - - targetOffset.x = offset.x - targetOffset.y = offset.y ; - - offsetIncrement = { - x: 0, - y: 0 - }; + if (thisObject.zoomTargetLevel > 10) { + amount = amount * 3 + } + if (thisObject.zoomTargetLevel > 15) { + amount = amount * 4 + } } + if (amount < 0) { + if (thisObject.zoomTargetLevel > -4) { + amount = amount * 2 + } - function zoomFontSize(baseSize, level) { + if (thisObject.zoomTargetLevel > 13) { + amount = amount * 3 + } - let zoomFactor = increment; // + increment * thisObject.zoomLevel / 100; - - if (level === undefined) { - - baseSize = baseSize * (1 + zoomFactor * thisObject.zoomLevel); - - } else { - - baseSize = baseSize * (1 + zoomFactor * level); - - } - - return baseSize; + if (thisObject.zoomTargetLevel > 19) { + amount = amount * 4 + } } - function fitIntoVisibleArea(point) { + if (thisObject.zoomTargetLevel + amount > 1000) { + return false + } + if (thisObject.zoomTargetLevel <= -27 && amount < 0) { + amount = amount / 4 + } + if (thisObject.zoomTargetLevel < -27 && amount > 0) { + amount = amount / 4 + } + + if (thisObject.zoomTargetLevel + amount < MIN_ZOOM_LEVEL) { + return false + } + + thisObject.zoomTargetLevel = thisObject.zoomTargetLevel + amount + + ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) / 3 + + let event = { + newLevel: thisObject.zoomTargetLevel, + newOffset: offset, + type: undefined + } + + if (amount > 0) { + event.type = 'Zoom In' + } else { + event.type = 'Zoom Out' + } + + thisObject.eventHandler.raiseEvent('Zoom Changed', event) + + return true + } + + function changeZoom (oldLevel, newLevel) { + let mouseNoZoom = unzoomThisPoint(thisObject.mousePosition, oldLevel) + let newMouse = zoomThisPoint(mouseNoZoom, newLevel) + + offset.x = offset.x - newMouse.x + thisObject.mousePosition.x + offset.y = offset.y - newMouse.y + thisObject.mousePosition.y + + targetOffset.x = offset.x + targetOffset.y = offset.y + + offsetIncrement = { + x: 0, + y: 0 + } + } + + function zoomFontSize (baseSize, level) { + let zoomFactor = increment // + increment * thisObject.zoomLevel / 100; + + if (level === undefined) { + baseSize = baseSize * (1 + zoomFactor * thisObject.zoomLevel) + } else { + baseSize = baseSize * (1 + zoomFactor * level) + } + + return baseSize + } + + function fitIntoVisibleArea (point) { /* Here we check the boundaries of the resulting points, so they dont go out of the visible area. */ - if (point.x > thisObject.visibleArea.bottomRight.x + 1) { - point.x = thisObject.visibleArea.bottomRight.x + 1; - } - - if (point.x < thisObject.visibleArea.topLeft.x - 1) { - point.x = thisObject.visibleArea.topLeft.x - 1; - } - - if (point.y > thisObject.visibleArea.bottomRight.y + 1) { - point.y = thisObject.visibleArea.bottomRight.y + 1; - } - - if (point.y < thisObject.visibleArea.topLeft.y - 1) { - point.y = thisObject.visibleArea.topLeft.y - 1; - } - - return point; + if (point.x > thisObject.visibleArea.bottomRight.x + 1) { + point.x = thisObject.visibleArea.bottomRight.x + 1 } - - function zoomThisPoint(point, level) { - - let zoomFactor = increment; // + increment * thisObject.zoomLevel / 100; - - if (level === undefined) { - - point.x = point.x * (1 + zoomFactor * thisObject.zoomLevel) + offset.x; - point.y = point.y * (1 + zoomFactor * thisObject.zoomLevel) + offset.y; - - } else { - - point.x = point.x * (1 + zoomFactor * level) + offset.x; - point.y = point.y * (1 + zoomFactor * level) + offset.y; - - } - - return point; + if (point.x < thisObject.visibleArea.topLeft.x - 1) { + point.x = thisObject.visibleArea.topLeft.x - 1 } - function unzoomThisPoint(pointWithZoom, level) { - - let pointWithoutZoom; - let zoomFactor = increment; // + increment * thisObject.zoomLevel / 100; - - if (level === undefined) { - - pointWithoutZoom = { - x: (pointWithZoom.x - offset.x) / (1 + zoomFactor * thisObject.zoomLevel), - y: (pointWithZoom.y - offset.y) / (1 + zoomFactor * thisObject.zoomLevel) - }; - - } else { - - pointWithoutZoom = { - x: (pointWithZoom.x - offset.x) / (1 + zoomFactor * level), - y: (pointWithZoom.y - offset.y) / (1 + zoomFactor * level) - }; - - } - return pointWithoutZoom; - + if (point.y > thisObject.visibleArea.bottomRight.y + 1) { + point.y = thisObject.visibleArea.bottomRight.y + 1 } - - - - function isThisPointVisible(point) { - - if (visibleArea === undefined) { - - getVisibleArea(); - - } - - if (point.x < visibleArea.topLeft.x || point.x > visibleArea.bottomRight.x || point.y < visibleArea.topLeft.y || point.y > visibleArea.bottomRight.y) { - return false; - } else { - return true; - } - + if (point.y < thisObject.visibleArea.topLeft.y - 1) { + point.y = thisObject.visibleArea.topLeft.y - 1 } + return point + } - function draw() { + function zoomThisPoint (point, level) { + let zoomFactor = increment // + increment * thisObject.zoomLevel / 100; + + if (level === undefined) { + point.x = point.x * (1 + zoomFactor * thisObject.zoomLevel) + offset.x + point.y = point.y * (1 + zoomFactor * thisObject.zoomLevel) + offset.y + } else { + point.x = point.x * (1 + zoomFactor * level) + offset.x + point.y = point.y * (1 + zoomFactor * level) + offset.y + } + + return point + } + + function unzoomThisPoint (pointWithZoom, level) { + let pointWithoutZoom + let zoomFactor = increment // + increment * thisObject.zoomLevel / 100; + + if (level === undefined) { + pointWithoutZoom = { + x: (pointWithZoom.x - offset.x) / (1 + zoomFactor * thisObject.zoomLevel), + y: (pointWithZoom.y - offset.y) / (1 + zoomFactor * thisObject.zoomLevel) + } + } else { + pointWithoutZoom = { + x: (pointWithZoom.x - offset.x) / (1 + zoomFactor * level), + y: (pointWithZoom.y - offset.y) / (1 + zoomFactor * level) + } + } + return pointWithoutZoom + } + + function isThisPointVisible (point) { + if (visibleArea === undefined) { + getVisibleArea() + } + + if (point.x < visibleArea.topLeft.x || point.x > visibleArea.bottomRight.x || point.y < visibleArea.topLeft.y || point.y > visibleArea.bottomRight.y) { + return false + } else { + return true + } + } + + function draw () { /* drawGrid(10); drawGrid(1); drawGrid(0.1); */ + } + + function drawGrid (step) { + let squareWidth = (thisObject.visibleArea.bottomRight.x - thisObject.visibleArea.bottomLeft.x) / step + squareWidth = squareWidth + squareWidth * increment * thisObject.zoomLevel + + let startingX = offset.x - Math.trunc(offset.x / squareWidth) * squareWidth + let startingY = offset.y - Math.trunc(offset.y / squareWidth) * squareWidth + let lineWidth = 10 / step + 10 / step * increment * thisObject.zoomLevel + + if (lineWidth < 0.5) { + return } - function drawGrid(step) { - - let squareWidth = (thisObject.visibleArea.bottomRight.x - thisObject.visibleArea.bottomLeft.x) / step; - squareWidth = squareWidth + squareWidth * increment * thisObject.zoomLevel; - - let startingX = offset.x - Math.trunc(offset.x / squareWidth) * squareWidth; - let startingY = offset.y - Math.trunc(offset.y / squareWidth) * squareWidth; - let lineWidth = 10 / step + 10 / step * increment * thisObject.zoomLevel; - - if (lineWidth < 0.5) { - return; - } - - if (lineWidth > 2) { - lineWidth = 2; - } - - browserCanvasContext.beginPath(); - - for (var i = startingX; i < thisObject.visibleArea.bottomRight.x; i = i + squareWidth) { - - for (var j = startingY; j < thisObject.visibleArea.bottomRight.y; j = j + squareWidth) { - - let point1 = { - x: thisObject.visibleArea.bottomLeft.x, - y: j - }; - - let point2 = { - x: thisObject.visibleArea.bottomRight.x, - y: j - }; - - browserCanvasContext.moveTo(point1.x, point1.y); - browserCanvasContext.lineTo(point2.x, point2.y); - } - - let point3 = { - x: i, - y: thisObject.visibleArea.topLeft.y - }; - - let point4 = { - x: i, - y: thisObject.visibleArea.bottomLeft.y - }; - - browserCanvasContext.moveTo(point3.x, point3.y); - browserCanvasContext.lineTo(point4.x, point4.y); - } - browserCanvasContext.closePath(); - browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.' + Math.trunc(lineWidth + 1) + ')'; - - browserCanvasContext.lineWidth = lineWidth; - - browserCanvasContext.stroke(); + if (lineWidth > 2) { + lineWidth = 2 } + browserCanvasContext.beginPath() + + for (var i = startingX; i < thisObject.visibleArea.bottomRight.x; i = i + squareWidth) { + for (var j = startingY; j < thisObject.visibleArea.bottomRight.y; j = j + squareWidth) { + let point1 = { + x: thisObject.visibleArea.bottomLeft.x, + y: j + } + + let point2 = { + x: thisObject.visibleArea.bottomRight.x, + y: j + } + + browserCanvasContext.moveTo(point1.x, point1.y) + browserCanvasContext.lineTo(point2.x, point2.y) + } + + let point3 = { + x: i, + y: thisObject.visibleArea.topLeft.y + } + + let point4 = { + x: i, + y: thisObject.visibleArea.bottomLeft.y + } + + browserCanvasContext.moveTo(point3.x, point3.y) + browserCanvasContext.lineTo(point4.x, point4.y) + } + browserCanvasContext.closePath() + browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.' + Math.trunc(lineWidth + 1) + ')' + + browserCanvasContext.lineWidth = lineWidth + + browserCanvasContext.stroke() + } } - - - diff --git a/VolumeBar.js b/VolumeBar.js index 5f865d7ab..dc86ab466 100644 --- a/VolumeBar.js +++ b/VolumeBar.js @@ -1,12 +1,10 @@ -function newVolumeBar() { + function newVolumeBar () { + var volumeBar = { + amountBuy: 0, + amountSell: 0, + begin: undefined, + end: undefined + } - var volumeBar = { - amountBuy: 0, - amountSell: 0, - begin: undefined, - end: undefined - }; - - return volumeBar; - -} \ No newline at end of file + return volumeBar + } diff --git a/WebDebugLog.js b/WebDebugLog.js index 7adc87a10..9845f59dc 100644 --- a/WebDebugLog.js +++ b/WebDebugLog.js @@ -1,20 +1,18 @@ - -function newWebDebugLog() { +  +function newWebDebugLog () { + let thisObject = { + write: write, + fileName: undefined + } - let thisObject = { - write: write, - fileName: undefined + return thisObject + + function write (pText) { + console.log(spacePad(thisObject.fileName, 50) + ' : ' + pText) + + function spacePad (str, max) { + str = str.toString() + return str.length < max ? spacePad(' ' + str, max) : str } - - return thisObject; - - function write(pText) { - - console.log(spacePad(thisObject.fileName, 50) + " : " + pText); - - function spacePad(str, max) { - str = str.toString(); - return str.length < max ? spacePad(" " + str, max) : str; - } - } -} \ No newline at end of file + } +}