diff --git a/Gruntfile.js b/Gruntfile.js index 7f2bdc9..4a33db7 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -16,36 +16,13 @@ module.exports = function(grunt) { }, js: { src: [ - 'js/Events.js', - 'js/Class.js', - 'js/Button.js', - 'js/Popup.js', - 'js/btnMove.js', - 'js/WordArt.js', - 'js/Shape.js', - 'js/AddShapeDialog.js', - 'js/Svg.js', - 'js/Keyboard.js', - 'js/SettingsWindow.js', - 'js/UpdatePanel.js', - 'js/PrinterPanel.js', - 'js/Help.js', - 'js/d3dServerInterfacing.js', - 'js/verticalShapes.js', - 'js/buttonbehaviors.js', - 'js/canvasDrawing.js', - 'js/previewRendering.js', - 'js/gcodeGenerating.js', - 'js/init_layout.js', - 'js/Printer.js', - 'js/Progressbar.js', - 'js/Thermometer.js', - 'js/utils.js', - 'js/sidebar.js', - 'js/Message.js', - 'js/main.js', - 'js/sketches.js' - ], + 'js/api/*.js', + 'js/settings/FormPanel.js', + 'js/settings/*.js', + 'js/*.js', + // make sure we put main.js last + '!js/main.js', + 'js/main.js', ], dest: 'www/js/<%= pkg.name %>.js' } }, @@ -113,7 +90,7 @@ module.exports = function(grunt) { }, watch: { javascript: { - files: ["js/*", '!www/js/<%= pkg.name %>.min.js', '!www/js/<%= pkg.name %>.js'], + files: ["js/**", '!www/js/<%= pkg.name %>.min.js', '!www/js/<%= pkg.name %>.js'], tasks: ["concat:js", "uglify:js"] // tasks: ["jshint", "concat", "uglify"] }, diff --git a/js/AddShapeDialog.js b/js/AddShapeDialog.js index 5a1ebce..ac14d8d 100644 --- a/js/AddShapeDialog.js +++ b/js/AddShapeDialog.js @@ -50,7 +50,7 @@ function updateShapePreview() { var c = canvas.getContext('2d'); var w = canvas.width; var h = canvas.height; - console.log(w,h); + //console.log(w,h); var r = w/2 - 20; var x0 = w/2; var y0 = h/2; diff --git a/js/Button.js b/js/Button.js index 78662d0..e235234 100644 --- a/js/Button.js +++ b/js/Button.js @@ -1,139 +1,150 @@ -(function($) { +/* + * This file is part of the Doodle3D project (http://doodle3d.com). + * + * Copyright (c) 2013, Doodle3D + * This software is licensed under the terms of the GNU GPL v2 or later. + * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. + */ - var clickEnabled = true; - - $.fn.Button = function() { - return $(this).each(function(){ - $.Button($(this)[0]); - }); +// prototype inheritance +// http://robertnyman.com/2008/10/06/javascript-inheritance-how-and-why/ +Button.prototype = new jQuery(); +function Button() { + + this.enabled = true; + + var _clickEnabled = true; + var _downTimerFPS = 20; + var _timer; + var _x,_y; + var _isDown = false; + var _self = this; + + // call jQuery constuctor + // http://blog.santoshrajan.com/2008/10/what-john-resig-did-not-tell-you.html + this.constructor.prototype.init.apply(this, arguments); + + // prevent multiple event handlers etc + // make sure you do a more general conversion last + if(this.data("isButton")) { + return; + } else { + this.data("isButton",true); + } + + this.enable = function() { + if(_self.enabled === true) { return; } + _self.removeClass("disabled"); + _self.enabled = true; }; - - $.Button = function(element) { - var downTimerFPS = 20; - var _timer = undefined; - var _x,_y; - var isDown = false; - - var updateCursor = function(e) { - // retrieve cursor position relative to element - if (e.offsetX != undefined) { - _x = e.offsetX; - _y = e.offsetY; - } else if(e.pageX != undefined) { + this.disable = function() { + if(_self.enabled === false) { return; } + _self.addClass("disabled"); + _self.enabled = false; + }; + // if the element starts with a disable class, we properly disable it + if(this.hasClass("disabled")) { + this.disable(); + } + + function updateCursor(e) { + // retrieve cursor position relative to element + if (e.offsetX !== undefined) { + _x = e.offsetX; + _y = e.offsetY; + } else { + var offset = _self.offset(); + if(e.pageX !== undefined) { // http://www.quirksmode.org/mobile/tableViewport_desktop.html#t11 - var offset = $(element).offset(); _x = e.pageX - offset.left; _y = e.pageY - offset.top; - } else if(e.originalEvent != undefined && e.originalEvent.pageX != undefined) { + } else if(e.originalEvent !== undefined && e.originalEvent.pageX !== undefined) { //http://css-tricks.com/the-javascript-behind-touch-friendly-sliders/ - var offset = $(element).offset(); _x = e.originalEvent.pageX - offset.left; _y = e.originalEvent.pageY - offset.top; } - - //android+chrome-specific hack - if (e.originalEvent.changedTouches != undefined) { - var offset = $(element).offset(); + + //android+chrome-specific hack + if (e.originalEvent.changedTouches !== undefined) { _x = e.originalEvent.changedTouches[0].pageX - offset.left; _y = e.originalEvent.changedTouches[0].pageY - offset.top; } } - - var startDownTimer = function() { - if (_timer==undefined) { - _timer = setInterval(onDownTimerInterval, 1000/downTimerFPS); - isDown = true; - } + } + function startDownTimer() { + if (_timer === undefined) { + _timer = setInterval(onDownTimerInterval, 1000/_downTimerFPS); + _isDown = true; } - - var stopDownTimer = function() { - clearInterval(_timer); - _timer = undefined; - isDown = false; - // _x = undefined; - // _y = undefined; + } + function stopDownTimer() { + clearInterval(_timer); + _timer = undefined; + _isDown = false; + // _x = undefined; + // _y = undefined; + } + function onDownTimerInterval() { + if(!_self.enabled) { return; } + if (_x !== undefined && _y !== undefined) { + _self.trigger("onButtonHold",{x:_x,y:_y}); + } else { + console.log("Button: warning... _x or _y not set..."); } - - var onDownTimerInterval = function() { - if (_x!=undefined && _y!=undefined) { - $(element).trigger("onButtonHold",{x:_x,y:_y}); - } else { - console.log("Button: warning... _x or _y not set..."); - } - } - - var onTouchStart = function(e) { - clickEnabled = false; - updateCursor(e); - startDownTimer(); - $(element).trigger("onButtonClick",{x:_x,y:_y}); - e.preventDefault(); - } - - var onTouchEnd = function(e) { - updateCursor(e); - stopDownTimer(); - } - - var onTouchMove = function(e) { - updateCursor(e); - startDownTimer(); - } - - var onMouseDown = function(e) { - updateCursor(e); - startDownTimer(); - } - - var onMouseUp = function(e) { - updateCursor(e); - stopDownTimer(); - } - - var onMouseMove = function(e) { - updateCursor(e); - if (isDown) onMouseDrag(e); - } - - var onMouseDrag = function(e) { - updateCursor(e); - } - - var onDocumentMouseUp = function(e) { - stopDownTimer(); - } - - var onClick = function(e) { - if(!clickEnabled) return; - updateCursor(e); - stopDownTimer(); - $(element).trigger("onButtonClick",{x:_x,y:_y}); - } - - var onStartDrag = function(e) { - } - - var onContextMenu = function(e) { - e.preventDefault(); - } - - //this needs to be done after the function declarations - - $(element).bind({ - touchstart: onTouchStart, - touchend: onTouchEnd, - touchmove: onTouchMove, - mousedown: onMouseDown, - mouseup: onMouseUp, - mousemove: onMouseMove, - contextmenu: onContextMenu, - click: onClick - }); - - $(document).on("mouseup", onDocumentMouseUp); - $(element).css("-webkit-user-select","none"); - $(element).css("-webkit-touch-callout","none"); - } -}(jQuery)); + // Event handlers + $(document).mouseup(function(e) { + stopDownTimer(); + }); + this.on("touchstart", function(e) { + if(!_self.enabled) { return; } + _clickEnabled = false; + updateCursor(e); + startDownTimer(); + _self.trigger("onButtonClick",{x:_x,y:_y}); + e.preventDefault(); + }); + this.on("touchend", function(e) { + updateCursor(e); + stopDownTimer(); + }); + this.on("touchmove", function(e) { + if(!_self.enabled) { return; } + updateCursor(e); + startDownTimer(); + }); + this.mousedown(function(e) { + if(!_self.enabled) { return; } + updateCursor(e); + startDownTimer(); + }); + this.mouseup(function(e) { + updateCursor(e); + stopDownTimer(); + }); + this.mousemove(function(e) { + if(!_self.enabled) { return; } + updateCursor(e); + //if (_isDown) mousedrag(e); + }); + //this.mousedrag(function(e) { + // updateCursor(e); + //}); + this.contextmenu(function(e) { + e.preventDefault(); + }); + this.click(function(e) { + if(!_self.enabled || !_clickEnabled) { return; } + updateCursor(e); + stopDownTimer(); + _self.trigger("onButtonClick",{x:_x,y:_y}); + }); +} + +// to work with multiple objects we need a jQuery plugin +$.fn.Button = function() { + return $(this).each(function(){ + new Button(this); + }); +}; \ No newline at end of file diff --git a/js/Class.js b/js/Class.js deleted file mode 100644 index afa6f1c..0000000 --- a/js/Class.js +++ /dev/null @@ -1,64 +0,0 @@ -/* Simple JavaScript Inheritance - * By John Resig http://ejohn.org/ - * MIT Licensed. - */ -// Inspired by base2 and Prototype -(function(){ - var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; - - // The base Class implementation (does nothing) - this.Class = function(){}; - - // Create a new Class that inherits from this class - Class.extend = function(prop) { - var _super = this.prototype; - - // Instantiate a base class (but only create the instance, - // don't run the init constructor) - initializing = true; - var prototype = new this(); - initializing = false; - - // Copy the properties over onto the new prototype - for (var name in prop) { - // Check if we're overwriting an existing function - prototype[name] = typeof prop[name] == "function" && - typeof _super[name] == "function" && fnTest.test(prop[name]) ? - (function(name, fn){ - return function() { - var tmp = this._super; - - // Add a new ._super() method that is the same method - // but on the super-class - this._super = _super[name]; - - // The method only need to be bound temporarily, so we - // remove it when we're done executing - var ret = fn.apply(this, arguments); - this._super = tmp; - - return ret; - }; - })(name, prop[name]) : - prop[name]; - } - - // The dummy class constructor - function Class() { - // All construction is actually done in the init method - if ( !initializing && this.init ) - this.init.apply(this, arguments); - } - - // Populate our constructed prototype object - Class.prototype = prototype; - - // Enforce the constructor to be what we expect - Class.prototype.constructor = Class; - - // And make this class extendable - Class.extend = arguments.callee; - - return Class; - }; -})(); \ No newline at end of file diff --git a/js/Help.js b/js/Help.js index 1e633ec..19e3df1 100644 --- a/js/Help.js +++ b/js/Help.js @@ -8,14 +8,14 @@ var grandTour; function GrandTour(_name) { - console.log("GrandTour"); + //console.log("GrandTour"); this.tour = ""; this.name = _name; this.active = false; var self = this; this.init = function() { - console.log("GrandTour >> f:init()"); + //console.log("GrandTour >> f:init()"); this.tour = function() { $('#help_d3dIntro').joyride({ @@ -48,9 +48,9 @@ function GrandTour(_name) { }; this.preRideCallback = function(index, tip) { - console.log("GrandTour >> f:preRideCallback() >> index: " + index); + //console.log("GrandTour >> f:preRideCallback() >> index: " + index); if (index == 0 && $.cookie("Doodle3DFirstTime") == "ridden") { - console.log("GrandTour >> f:preRideCallback() >> we've been here before..."); + //console.log("GrandTour >> f:preRideCallback() >> we've been here before..."); if ($.cookie("grandTourFinished")) { // grand tour was previously finished (eh.. is that useful?) @@ -82,7 +82,7 @@ function GrandTour(_name) { if (dataset.action != undefined) { switch (dataset.action) { case "showMessage": - console.log(" action: showMessage"); + //console.log(" action: showMessage"); message.set("This is a status message...", Message.NOTICE); break; } @@ -111,7 +111,7 @@ function GrandTour(_name) { } if (index < $(this)[0].$tip_content.length - 1) { - console.log("GrandTour >> f:postRideCallback() >> tour terminated before its true end"); + //console.log("GrandTour >> f:postRideCallback() >> tour terminated before its true end"); // tour wasn't finished // tour was ended prematurely. For only the first few visits, nag the user about being able to revisit the tour.. @@ -121,7 +121,7 @@ function GrandTour(_name) { // infoReminderTour.start(); } else { // tour was finished - console.log("GrandTour >> f:postRideCallback() >> tour ended at its true end"); + //console.log("GrandTour >> f:postRideCallback() >> tour ended at its true end"); // we should be at the end... if (!$.cookie("grandTourFinished") && parseInt($.cookie("Doodle3DVisitCounter")) < helpTours.numTimesToShowNagPopup) { helpTours.startTour(helpTours.INFOREMINDER, helpTours); @@ -132,7 +132,7 @@ function GrandTour(_name) { }; this.start = function() { - console.log("GrandTour >> f:start() >> this: " , this); + //console.log("GrandTour >> f:start() >> this: " , this); this.active = true; $(window).joyride('restart'); // self.tour(); @@ -141,14 +141,14 @@ function GrandTour(_name) { var infoReminderTour; function InfoReminderTour(_name) { - console.log("InfoReminderTour"); + //console.log("InfoReminderTour"); this.tour = ""; this.name = _name; this.active = false; var self = this; this.init = function(callback) { - console.log("InfoReminderTour >> f:init()"); + //console.log("InfoReminderTour >> f:init()"); this.tour = function() { $('#help_InfoReminder').joyride({ @@ -173,19 +173,19 @@ function InfoReminderTour(_name) { }; this.preRideCallback = function(index, tip) { - console.log("InfoReminderTour >> f:preRideCallback() >> index: " + index + ", tip: " , tip); + //console.log("InfoReminderTour >> f:preRideCallback() >> index: " + index + ", tip: " , tip); }; this.postStepCallback = function(index, tip) { - console.log("InfoReminderTour >> f:postStepCallback() >> index: " + index + ", tip: " , tip); + //console.log("InfoReminderTour >> f:postStepCallback() >> index: " + index + ", tip: " , tip); }; this.postRideCallback = function(index, tip) { - console.log("InfoReminderTour >> f:postRideCallback() >> index: " + index + ", tip: " , tip); + //console.log("InfoReminderTour >> f:postRideCallback() >> index: " + index + ", tip: " , tip); this.active = false; $(document).trigger(helpTours.TOURFINISHED, self.name); }; this.start = function() { - console.log("InfoReminderTour >> f:start()"); + //console.log("InfoReminderTour >> f:start()"); this.active = true; $(window).joyride('restart'); // self.tour(); @@ -193,7 +193,7 @@ function InfoReminderTour(_name) { } function initHelp() { - console.log("f:initHelp()"); + //console.log("f:initHelp()"); // track number of visits of this user if ($.cookie("Doodle3DVisitCounter") == null) { @@ -204,7 +204,7 @@ function initHelp() { // load the html file which describes the tour contents $("#helpContainer").load("helpcontent.html", function() { - console.log("helpContent loaded"); + //console.log("helpContent loaded"); helpTours = new HelpTours(); @@ -212,7 +212,7 @@ function initHelp() { if (parseInt($.cookie("Doodle3DVisitCounter")) < helpTours.numTimesToShowNagPopup) { - console.log("initHelp >> Doodle3DFirstTime cookie is set, Doodle3DVisitCounter is < 4"); + //console.log("initHelp >> Doodle3DFirstTime cookie is set, Doodle3DVisitCounter is < 4"); if ($.cookie("Doodle3DFirstTime") != "ridden") { setTimeout(helpTours.startTour, 750, helpTours.tours.grandTour, helpTours); } else { @@ -239,7 +239,7 @@ function initHelp() { var helpTours; function HelpTours() { - console.log("HelpTours"); + //console.log("HelpTours"); this.numTimesToShowNagPopup = 2; @@ -257,7 +257,7 @@ function HelpTours() { var self = this; this.init = function(callback) { - console.log("HelpTours >> f:init >> self: " + self); + //console.log("HelpTours >> f:init >> self: " + self); $(document).on(this.TOURFINISHED, this.tourEnded); grandTour = new GrandTour(this.WELCOMETOUR); @@ -265,7 +265,7 @@ function HelpTours() { // this.tours["grandTour"] = self.WELCOMETOUR; // this.tours["infoReminderTour "]= self.INFOREMINDER; - console.log("HelpTours >> f:init >> this.tours: " , this.tours); + //console.log("HelpTours >> f:init >> this.tours: " , this.tours); if (callback != undefined) callback(); }; @@ -282,8 +282,8 @@ function HelpTours() { switch (which) { case scope.WELCOMETOUR: // do welcometour -// console.log("HelpTours >> f:startTour >> case this.WELCOMETOUR >> scope.tourActive = " + scope.tourActive); - console.log("HelpTours >> f:startTour >> case this.WELCOMETOUR"); + //console.log("HelpTours >> f:startTour >> case this.WELCOMETOUR >> scope.tourActive = " + scope.tourActive); + //console.log("HelpTours >> f:startTour >> case this.WELCOMETOUR"); if (scope.tourActive) { if (scope.currActiveTour.active == true) { $(window).joyride('end'); @@ -304,8 +304,8 @@ function HelpTours() { break; case self.INFOREMINDER: // do info reminder -// console.log("HelpTours >> f:startTour >> case self.INFOREMINDER >> scope.tourActive = " + scope.tourActive); - console.log("HelpTours >> f:startTour >> case self.INFOREMINDER"); +// console.log("HelpTours >> f:startTour >> case self.INFOREMINDER >> scope.tourActive = " + scope.tourActive); + //console.log("HelpTours >> f:startTour >> case self.INFOREMINDER"); if (scope.tourActive) { // console.log(" killing previous joyride... "); if (scope.currActiveTour.active == true) { @@ -330,7 +330,7 @@ function HelpTours() { } this.tourEnded = function(e, n) { - console.log("HelpTours >> f:tourEnded >> self.tourActive: " + self.tourActive + ", name: " + n); + //console.log("HelpTours >> f:tourEnded >> self.tourActive: " + self.tourActive + ", name: " + n); $(window).joyride('destroy'); self.currActiveTour = undefined; diff --git a/js/Printer.js b/js/Printer.js index 910456b..f5f3dc5 100644 --- a/js/Printer.js +++ b/js/Printer.js @@ -65,12 +65,12 @@ function Printer() { var self = this; this.init = function() { - console.log("Printer:init"); + //console.log("Printer:init"); //this.wifiboxURL = "http://" + window.location.host + "/cgi-bin/d3dapi"; //this.wifiboxURL = "http://192.168.5.1/cgi-bin/d3dapi"; this.wifiboxURL = wifiboxURL; //this.wifiboxURL = "proxy5.php"; - console.log(" wifiboxURL: ",this.wifiboxURL); + //console.log(" wifiboxURL: ",this.wifiboxURL); if(autoUpdate) { this.startStatusCheckInterval(); diff --git a/js/PrinterPanel.js b/js/PrinterPanel.js deleted file mode 100644 index 8c95ded..0000000 --- a/js/PrinterPanel.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of the Doodle3D project (http://doodle3d.com). - * - * Copyright (c) 2013, Doodle3D - * This software is licensed under the terms of the GNU GPL v2 or later. - * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. - */ - -function PrinterPanel() { - this.wifiboxURL; - this.element; - - this.retryDelay = 1000; - this.retryDelayer; // setTimout instance - //this.timeoutTime = 3000; - - this.printerType; - this.printerSettingsNames; - - var self = this; - - this.init = function(wifiboxURL,element) { - self.wifiboxURL = wifiboxURL; - self.element = element; - - self.printerSelector = element.find("#printerType"); - self.printerSelector.change(self.printerSelectorChanged); - - var formElements = element.find("[name]"); - self.printerSettingsNames = []; - formElements.each( function(index,element) { - self.printerSettingsNames.push(element.name); - }); - - var gcodePanel = element.find("#gcodePanel"); - gcodePanel.coolfieldset({collapsed:true}); - } - this.printerSelectorChanged = function(e) { - console.log("PrinterPanel:printerSelectorChanged"); - console.log("self: ", self); - self.printerType = self.printerSelector.find("option:selected").val(); - self.savePrinterType(self.loadPrinterSettings); - } - - this.savePrinterType = function(complete) { - console.log("PrinterPanel:savePrinterType"); - var postData = {}; - postData[self.printerSelector.attr("name")] = self.printerType; - console.log("postData: ",postData); - $.ajax({ - url: self.wifiboxURL + "/config/", - type: "POST", - dataType: 'json', - data: postData, - success: function(response){ - console.log("PrinterPanel:savePrinterType response: ",response); - if(complete) complete(); - } - }).fail(function() { - console.log("PrinterPanel:savePrinterType: failed"); - }); - } - this.loadPrinterSettings = function() { - console.log("PrinterPanel:loadPrinterSettings"); - console.log(" self.printerSettingsNames: ",self.printerSettingsNames); - var getData = {}; - $.each(self.printerSettingsNames, function(key, val) { - getData[val] = ""; - }); - console.log("getData: ",getData); - $.ajax({ - url: self.wifiboxURL + "/config/", - dataType: 'json', - data: getData, - success: function(response){ - console.log("PrinterPanel:loadPrinterSettings response: ",response); - - self.fillForm(response.data,self.element); - } - }).fail(function() { - console.log("PrinterPanel:loadPrinterSettings: failed"); - }); - } -} diff --git a/js/Progressbar.js b/js/Progressbar.js index 12a03cb..26ff170 100644 --- a/js/Progressbar.js +++ b/js/Progressbar.js @@ -45,7 +45,7 @@ function Progressbar() { var self = this; this.progressbarBGImg.onload = function() { - console.log("progressbarBGImg img loaded"); + //console.log("progressbarBGImg img loaded"); // self.isInitted = true; // self.update(self.currentTemperature, self.targetTemperature); diff --git a/js/SettingsWindow.js b/js/SettingsWindow.js deleted file mode 100644 index 4214c09..0000000 --- a/js/SettingsWindow.js +++ /dev/null @@ -1,792 +0,0 @@ -/* - * This file is part of the Doodle3D project (http://doodle3d.com). - * - * Copyright (c) 2013, Doodle3D - * This software is licensed under the terms of the GNU GPL v2 or later. - * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. - */ - -//these settings are defined in the firmware (conf_defaults.lua) and will be initialized in loadSettings() -var settings = {}; -var settingsPopup; -//wrapper to prevent scoping issues in showSettings() -function openSettingsWindow() { - settingsWindow.loadSettings(function() { // reload settings - settingsPopup.open(); - }); -} - -function SettingsWindow() { - this.wifiboxURL; - this.wifiboxCGIBinURL; - this.window; - this.btnOK; - this.form; - this.timeoutTime = 3000; - this.saveSettingsTimeoutTime = 8000; - this.retryDelay = 2000; // retry setTimout delay - this.retryRetrieveNetworkStatusDelayTime = 1000;// retry setTimout delay - - this.retryLoadSettingsDelay; // retry setTimout instance - this.retrySaveSettingsDelay; // retry setTimout instance - this.retryResetSettingsDelay; // retry setTimout instance - this.retryRetrieveNetworkStatusDelay;// retry setTimout instance - - this.apFieldSet; - this.clientFieldSet; - this.restoreStateField; - this.networks; - this.currentNetwork; // the ssid of the network the box is on - this.selectedNetwork; // the ssid of the selected network in the client mode settings - this.currentLocalIP = ""; - this.clientModeState = SettingsWindow.NOT_CONNECTED; - this.currentAP; - this.apModeState = SettingsWindow.NO_AP; - - // after switching wifi network or creating a access point we delay the status retrieval - // because the webserver needs time to switch - this.retrieveNetworkStatusDelay; // setTimout delay - this.retrieveNetworkStatusDelayTime = 1000; - - this.restoredStateHideDelayTime = 3000; - this.restoredStateHideDelay; // setTimout instance - - // Events - SettingsWindow.SETTINGS_LOADED = "settingsLoaded"; - - // network client mode states - SettingsWindow.NOT_CONNECTED = "not connected"; // also used as first item in networks list - SettingsWindow.CONNECTED = "connected"; - SettingsWindow.CONNECTING = "connecting"; - SettingsWindow.CONNECTING_FAILED = "connecting failed"; - - // network access point mode states - SettingsWindow.NO_AP = "no ap"; - SettingsWindow.AP = "ap"; - SettingsWindow.CREATING_AP = "creating ap"; - - SettingsWindow.API_CONNECTING_FAILED = -1; - SettingsWindow.API_NOT_CONNECTED = 0; - SettingsWindow.API_CONNECTING = 1; - SettingsWindow.API_CONNECTED = 2; - SettingsWindow.API_CREATING = 3; - SettingsWindow.API_CREATED = 4; - - // network mode - SettingsWindow.NETWORK_MODE_NEITHER = "neither"; - SettingsWindow.NETWORK_MODE_CLIENT = "clientMode"; - SettingsWindow.NETWORK_MODE_ACCESS_POINT = "accessPointMode"; - - this.networkMode = SettingsWindow.NETWORK_MODE_NEITHER; - - this.updatePanel = new UpdatePanel(); - this.printerPanel = new PrinterPanel(); - - var self = this; - - this.init = function(wifiboxURL,wifiboxCGIBinURL) { - this.wifiboxURL = wifiboxURL; - this.wifiboxCGIBinURL = wifiboxCGIBinURL; - - this.window = $("#popupSettings"); - this.btnOK = this.window.find(".btnOK"); - settingsPopup = new Popup($("#popupSettings"), $("#popupMask")); - settingsPopup.setEnterEnabled(false); - settingsPopup.setAutoCloseEnabled(false); - - enableButton(this.btnOK,settingsPopup.commit); - $("#popupSettings").bind("onPopupCancel", function() { settingsPopup.close(); } ); - $("#popupSettings").bind("onPopupCommit", self.submitwindow); - - this.window.find("#settingsContainer").load("settings.html", function() { - console.log("Settings:finished loading settings.html, now loading settings..."); - - self.form = self.window.find("form"); - self.form.submit(function (e) { self.submitwindow(e); }); - - $.ajax({ - url: self.wifiboxURL + "/printer/listall", - dataType: 'json', - timeout: self.timeoutTime, - success: function(response) { - console.log("Settings:printer/listall response: ",response.data.printers); - - $.each(response.data.printers, function(key, value) { - // console.log(key,value); - $('#printerType').append($('").val(SettingsWindow.NOT_CONNECTED).html("not connected") - ); - $.each(networks, function(index,element) { - if(element.ssid == self.currentNetwork) { - foundCurrentNetwork = true; - } - networkSelector.append( - $("").val(element.ssid).html(element.ssid) - ); - self.networks[element.ssid] = element; - }); - if(foundCurrentNetwork) { - networkSelector.val(self.currentNetwork); - self.selectNetwork(self.currentNetwork); - } - } - } - }).fail(function() { - - }); - } - }; - - this.retrieveNetworkStatus = function(connecting) { - //console.log("Settings:retrieveNetworkStatus"); - if (communicateWithWifibox) { - $.ajax({ - url: self.wifiboxURL + "/network/status", - type: "GET", - dataType: 'json', - timeout: self.timeoutTime, - success: function(response){ - console.log("Settings:retrieveNetworkStatus response: ",response); - if(response.status == "error") { - - } else { - var data = response.data; - - if(typeof data.status === 'string') { - data.status = parseInt(data.status); - } - //console.log(" data.status: ",data.status,data.statusMessage); - - // Determine which network settings to show - switch(data.status) { - case SettingsWindow.API_NOT_CONNECTED: - //console.log(" not connected & not a access point"); - self.apFieldSet.show(); - self.clientFieldSet.show(); - - self.networkMode = SettingsWindow.NETWORK_MODE_NEITHER; - break; - case SettingsWindow.API_CONNECTING_FAILED: - case SettingsWindow.API_CONNECTING: - case SettingsWindow.API_CONNECTED: - //console.log(" client mode"); - self.form.find("#client").prop('checked',true); - - self.apFieldSet.hide(); - self.clientFieldSet.show(); - - if(data.status == SettingsWindow.API_CONNECTED) { - var networkSelector = self.form.find("#network"); - networkSelector.val(data.ssid); - - self.currentNetwork = data.ssid; - self.currentLocalIP = data.localip; - self.selectNetwork(data.ssid); - } else { - self.currentLocalIP = ""; - } - self.networkMode = SettingsWindow.NETWORK_MODE_CLIENT; - break; - case SettingsWindow.API_CREATING: - case SettingsWindow.API_CREATED: - //console.log(" access point mode"); - self.form.find("#ap").prop('checked',true); - - self.apFieldSet.show(); - self.clientFieldSet.hide(); - - self.currentNetwork = undefined; - self.selectNetwork(SettingsWindow.NOT_CONNECTED); - var networkSelector = self.form.find("#network"); - networkSelector.val(SettingsWindow.NOT_CONNECTED); - - if(data.ssid && data.status == SettingsWindow.API_CREATED) { - self.currentAP = data.ssid; - } - self.networkMode = SettingsWindow.NETWORK_MODE_ACCESS_POINT; - break; - } - self.updatePanel.setNetworkMode(self.networkMode); - - // update status message - switch(data.status) { - case SettingsWindow.API_CONNECTING_FAILED: - self.setClientModeState(SettingsWindow.CONNECTING_FAILED,data.statusMessage); - self.setAPModeState(SettingsWindow.NO_AP,""); - break; - case SettingsWindow.API_NOT_CONNECTED: - self.setClientModeState(SettingsWindow.NOT_CONNECTED,""); - self.setAPModeState(SettingsWindow.NO_AP,""); - break; - case SettingsWindow.API_CONNECTING: - self.setClientModeState(SettingsWindow.CONNECTING,""); - self.setAPModeState(SettingsWindow.NO_AP,""); - break; - case SettingsWindow.API_CONNECTED: - self.setClientModeState(SettingsWindow.CONNECTED,""); - self.setAPModeState(SettingsWindow.NO_AP,""); - break; - case SettingsWindow.API_CREATING: - self.setClientModeState(SettingsWindow.NOT_CONNECTED,""); - self.setAPModeState(SettingsWindow.CREATING_AP,""); - break; - case SettingsWindow.API_CREATED: - self.setClientModeState(SettingsWindow.NOT_CONNECTED,""); - self.setAPModeState(SettingsWindow.AP,""); - break; - } - - // Keep checking for updates? - if(connecting) { - switch(data.status) { - case SettingsWindow.API_CONNECTING: - case SettingsWindow.API_CREATING: - clearTimeout(self.retryRetrieveNetworkStatusDelay); - self.retryRetrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(connecting); },self.retryRetrieveNetworkStatusDelayTime); // retry after delay - break; - } - } - } - } - }).fail(function() { - console.log("Settings:retrieveNetworkStatus: failed"); - clearTimeout(self.retryRetrieveNetworkStatusDelay); - self.retryRetrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(connecting); },self.retryDelay); // retry after delay - }); - } - }; - - this.networkSelectorChanged = function(e) { - var selectedOption = $(this).find("option:selected"); - self.selectNetwork(selectedOption.val()); - }; - - this.selectNetwork = function(ssid) { - console.log("select network: ",ssid); - if(ssid == "") return; - console.log(" checked"); - this.selectedNetwork = ssid; - if(this.networks == undefined || ssid == SettingsWindow.NOT_CONNECTED) { - this.hideWiFiPassword(); - } else { - var network = this.networks[ssid]; - if(network.encryption == "none") { - this.hideWiFiPassword(); - } else { - this.showWiFiPassword(); - } - this.form.find("#password").val(""); - } - }; - - this.showWiFiPassword = function() { - this.form.find("#passwordLabel").show(); - this.form.find("#password").show(); - }; - - this.hideWiFiPassword = function() { - this.form.find("#passwordLabel").hide(); - this.form.find("#password").hide(); - }; - - this.setClientModeState = function(state,msg) { - var field = this.form.find("#clientModeState"); - var btnConnect = self.form.find("#connectToNetwork"); - switch(state) { - case SettingsWindow.NOT_CONNECTED: - btnConnect.removeAttr("disabled"); - field.html("Not connected"); - break; - case SettingsWindow.CONNECTED: - btnConnect.removeAttr("disabled"); - - var fieldText = "Connected to: "+this.currentNetwork+"."; - if(this.currentLocalIP != undefined && this.currentLocalIP != "") { - var a = ""+this.currentLocalIP+""; - fieldText += " (IP: "+a+")"; - } - field.html(fieldText); - break; - case SettingsWindow.CONNECTING: - btnConnect.attr("disabled", true); - field.html("Connecting... Reconnect by connecting your device to "+this.selectedNetwork+" and going to connect.doodle3d.com"); - break; - case SettingsWindow.CONNECTING_FAILED: - btnConnect.removeAttr("disabled"); - field.html(msg); - break; - } - this.clientModeState = state; - }; - - this.setAPModeState = function(state,msg) { - var field = this.form.find("#apModeState"); - var btnCreate = this.form.find("#createAP"); - switch(state) { - case SettingsWindow.NO_AP: - btnCreate.removeAttr("disabled"); - field.html("Not currently a access point"); - break; - case SettingsWindow.AP: - btnCreate.removeAttr("disabled"); - field.html("Is access point: "+this.currentAP+""); - break; - case SettingsWindow.CREATING_AP: - btnCreate.attr("disabled", true); - field.html("Creating access point... Reconnect by connecting your device to "+settings.substituted_ssid+" and going to draw.doodle3d.com"); - break; - } - this.apModeState = state; - }; - - this.connectToNetwork = function() { - console.log("connectToNetwork"); - if(self.selectedNetwork == undefined) return; - var postData = { - ssid:self.selectedNetwork, - phrase:self.form.find("#password").val(), - recreate:true - }; - - console.log(" postData: ",postData); - if (communicateWithWifibox) { - - // save network related settings and on complete, connect to network - self.saveSettings(self.readForm(),function(success) { - if(!success) return; - $.ajax({ - url: self.wifiboxCGIBinURL + "/network/associate", - type: "POST", - data: postData, - dataType: 'json', - timeout: self.timeoutTime, - success: function(response){ - console.log("Settings:connectToNetwork response: ",response); - } - }).fail(function() { - console.log("Settings:connectToNetwork: timeout (normal behavior)"); - //clearTimeout(self.retrySaveSettingsDelay); - //self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings() },self.retryDelay); // retry after delay - }); - }); - } - self.setClientModeState(SettingsWindow.CONNECTING,""); - - // after switching wifi network or creating a access point we delay the status retrieval - // because the webserver needs time to switch - clearTimeout(self.retrieveNetworkStatusDelay); - self.retrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(true); },self.retrieveNetworkStatusDelayTime); - }; - - this.createAP = function() { - console.log("createAP"); - if (communicateWithWifibox) { - - // save network related settings and on complete, create access point - self.saveSettings(self.readForm(),function(success) { - if(!success) return; - self.setAPModeState(SettingsWindow.CREATING_AP); // get latest substituted ssid - $.ajax({ - url: self.wifiboxCGIBinURL + "/network/openap", - type: "POST", - dataType: 'json', - timeout: self.timeoutTime, - success: function(response){ - console.log("Settings:createAP response: ",response); - } - }).fail(function() { - console.log("Settings:createAP: timeout (normal behavior)"); - //clearTimeout(self.retrySaveSettingsDelay); - //self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings() },self.retryDelay); // retry after delay - }); - - self.setAPModeState(SettingsWindow.CREATING_AP,""); - - // after switching wifi network or creating a access point we delay the status retrieval - // because the webserver needs time to switch - clearTimeout(self.retrieveNetworkStatusDelay); - self.retrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(true); },self.retrieveNetworkStatusDelayTime); - }); - } - }; -} - -/************************* - * - * - * FROM DOODLE3D.INI - * - */ -//TODO: find all references to these variables, replace them and finally remove these. -var objectHeight = 20; -var layerHeight = .2; -//var wallThickness = .5; -//var hop = 0; -//var speed = 70; -//var travelSpeed = 200; -var enableTraveling = true; -//var filamentThickness = 2.89; -var minScale = .3; -var maxScale = 1; -var shape = "%"; -var twists = 0; -//var useSubLayers = true; -//var debug = false; // debug moved to main.js -var loglevel = 2; -//var zOffset = 0; -var serverport = 8888; -var autoLoadImage = "hand.txt"; -var loadOffset = [0, 0]; // x en y ? -var showWarmUp = true; -var loopAlways = false; -var firstLayerSlow = true; -var useSubpathColors = false; -var autoWarmUp = true; -//var maxObjectHeight = 150; -var maxScaleDifference = .1; -var frameRate = 60; -var quitOnEscape = true; -var screenToMillimeterScale = .3; // 0.3 -//var targetTemperature = 220; -//var simplifyiterations = 10; -//var simplifyminNumPoints = 15; -//var simplifyminDistance = 3; -//var retractionspeed = 50; -//var retractionminDistance = 5; -//var retractionamount = 3; -var sideis3D = true; -var sidevisible = true; -var sidebounds = [900, 210, 131, 390]; -var sideborder = [880, 169, 2, 471]; -var windowbounds = [0, 0, 800, 500]; -var windowcenter = true; -var windowfullscreen = false; -var autoWarmUpCommand = "M104 S230"; -//var checkTemperatureInterval = 3; -var autoWarmUpDelay = 3; diff --git a/js/Shape.js b/js/Shape.js index 722370b..ebf1c59 100644 --- a/js/Shape.js +++ b/js/Shape.js @@ -40,7 +40,7 @@ function endShape() { } function getBounds(points) { - var xMin=9999,xMax=-9999,yMin=9999,yMax=-9999; + var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity; for (var i=0; i_element: ",_element); + _configAPI.init(wifiboxURL,wifiboxCGIBinURL); + }; + + //this.readForm = function(form) { + this.readForm = function(form) { + //console.log("FormPanel:readForm"); + if(!form) form = _element; // if no form specified, read whole panel form + //console.log("FormPanel"); + var settings = {}; + // Read all selects + var selects = form.find("select"); + selects.each( function(index,element) { + var elem = $(element); + //var fieldName = elem.attr('name'); + if(elem.attr('name') != "") { + settings[elem.attr('name')] = elem.val(); + } + }); + // Read all inputs + var inputs = form.find("input"); + inputs.each( function(index,element) { + var elem = $(element); + if(elem.attr('name') != "") { + switch(elem.attr("type")) { + case "text": + case "number": + settings[elem.attr('name')] = elem.val(); + break; + case "checkbox": + settings[elem.attr('name')] = elem.prop('checked'); + break; + } + } + }); + // Read all textareas + var textareas = form.find("textarea"); + textareas.each( function(index,element) { + var elem = $(element); + settings[elem.attr('name')] = elem.val(); + }); + return settings; + }; + + this.fillForm = function(settings,form) { + //console.log("FormPanel:fillForm"); + if(!form) form = _element; // if no form specified, fill whole panel form + //console.log(" form: ",form); + + clearValidationErrors(); + + //fill form with loaded settings + var selects = form.find("select"); + selects.each( function(index,element) { + var elem = $(element); + elem.val(settings[elem.attr('name')]); + }); + var inputs = form.find("input"); + inputs.each( function(index,element) { + var elem = $(element); + //console.log("printer setting input: ",index,element.attr("type"),element.attr('name')); //,element); + switch(elem.attr("type")) { + case "text": + case "number": + elem.val(settings[elem.attr('name')]); + break; + case "checkbox": + elem.prop('checked', settings[elem.attr('name')]); + break; + } + }); + var textareas = form.find("textarea"); + textareas.each( function(index,element) { + var elem = $(element); + var value = settings[elem.attr('name')]; + elem.val(value); + }); + }; + + this.saveSettings = function(newSettings,complete) { + //console.log(" newSettings: ",newSettings); + _configAPI.save(newSettings,function(data) { + var validation = data.validation; + //console.log(" validation: ",validation); + clearValidationErrors(); + var validated = true; + $.each(validation, function(key, val) { + if (val != "ok") { + console.log("ERROR: setting '" + key + "' not successfully set. Message: " + val); + displayValidationError(key,val); + validated = false; + } + }); + if(complete) complete(validated, data); + }, function() { + console.log("Settings:saveSettings: failed"); + clearTimeout(_retrySaveSettingsDelay); + _retrySaveSettingsDelay = setTimeout(function() { _self.saveSettings(newSettings,complete); },_retryDelay); // retry after delay + }); + }; + function displayValidationError(key,msg) { + var formElement = _element.find("[name|='"+key+"']"); + formElement.addClass("error"); + var errorMsg = "

"+msg+"

"; + formElement.after(errorMsg); + }; + function clearValidationErrors() { + _element.find(".errorMsg").remove(); + _element.find(".error").removeClass("error"); + }; + + this.loadAllSettings = function(complete) { + _configAPI.loadAll(complete,function() { + clearTimeout(_retryLoadAllSettingsDelay); + _retryLoadAllSettingsDelay = setTimeout(function() { _self.loadAllSettings(complete); },_retryDelay); // retry after delay + }); + }; + this.loadSettings = function(targetSettings,complete) { + _configAPI.load(targetSettings,complete,function() { + clearTimeout(_retryLoadSettingsDelay); + _retryLoadSettingsDelay = setTimeout(function() { _self.loadSettings(targetSettings,complete); },_retryDelay); // retry after delay + }); + }; + + this.resetAllSettings = function(complete) { + _configAPI.resetAll(complete,function() { + clearTimeout(_retryResetSettingsDelay); + _retryResetSettingsDelay = setTimeout(function() { _self.resetAllSettings(complete); },_retryDelay); // retry after delay + }); + }; +} diff --git a/js/settings/NetworkPanel.js b/js/settings/NetworkPanel.js new file mode 100644 index 0000000..63f2e2c --- /dev/null +++ b/js/settings/NetworkPanel.js @@ -0,0 +1,341 @@ +/* + * This file is part of the Doodle3D project (http://doodle3d.com). + * + * Copyright (c) 2013, Doodle3D + * This software is licensed under the terms of the GNU GPL v2 or later. + * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. + */ + +function NetworkPanel() { + + var NOT_CONNECTED = "not connected"; // used as first item in networks list + + // network mode + NetworkPanel.NETWORK_MODE = { + NEITHER: "neither", + CLIENT: "clientMode", + ACCESS_POINT: "accessPointMode" + }; + var _networkMode = NetworkPanel.NETWORK_MODE.NEITHER; + var _networkModeChangedHandler; + + var _form = new FormPanel(); + var _api = new NetworkAPI(); + var _networks = {}; + var _currentNetwork; // the ssid of the network the box is on + var _selectedNetwork; // the ssid of the selected network in the client mode settings + var _substituted_ssid; // the substituted ssid (displayed during creation) + var _currentLocalIP = ""; + var _currentAP; + var _currentNetworkStatus; + + var _retryDelay = 2000; + //var _retryRefreshNetworksDelay; + var _retryRetrieveStatusDelayTime = 1000; + var _retryRetrieveStatusDelay; + // after switching wifi network or creating a access point we delay the status retrieval + // because the webserver needs time to switch + var _retrieveNetworkStatusDelayTime = 1000; + var _retrieveNetworkStatusDelay; + + // ui elements + var _element; + var _networkSelector; + var _apFieldSet; + var _clientFieldSet; + var _apRadioButton; + var _clientRadioButton; + var _btnRefresh + var _btnConnect; + var _btnCreate; + var _passwordField; + var _passwordLabel; + var _clientStateDisplay; + var _apModeStateDisplay; + + var _self = this; + + this.init = function(wifiboxURL,wifiboxCGIBinURL,panelElement) { + //console.log("NetworkPanel:init"); + + _form.init(wifiboxURL,wifiboxCGIBinURL,panelElement) + + _api.init(wifiboxURL,wifiboxCGIBinURL); + + _element = panelElement; + _apRadioButton = _element.find("#ap"); + _clientRadioButton = _element.find("#client"); + _btnRefresh = _element.find("#refreshNetworks"); + _btnConnect = _element.find("#connectToNetwork"); + _btnCreate = _element.find("#createAP"); + _networkSelector = _element.find("#network"); + _apFieldSet = _element.find("#apSettings"); + _clientFieldSet = _element.find("#clientSettings"); + _passwordField = _element.find("#password"); + _passwordLabel = _element.find("#passwordLabel"); + _clientStateDisplay = _element.find("#clientModeState"); + _apModeStateDisplay = _element.find("#apModeState"); + + _apRadioButton.parent().on('touchstart mousedown',showAPSettings); + _clientRadioButton.parent().on('touchstart mousedown',showClientSettings); + _btnRefresh.on('touchstart mousedown',onRefreshClick); + _btnConnect.on('touchstart mousedown',_self.connectToNetwork); + _btnCreate.on('touchstart mousedown',_self.createAP); + _networkSelector.change(networkSelectorChanged); + } + /* + * Handlers + */ + function showAPSettings() { + _apFieldSet.show(); + _clientFieldSet.hide(); + }; + function showClientSettings() { + _clientFieldSet.show(); + _apFieldSet.hide(); + }; + function onRefreshClick() { + _btnRefresh.attr("disabled", true); + _self.refreshNetworks(function() { + _btnRefresh.removeAttr("disabled"); + }) + } + function networkSelectorChanged(e) { + var selectedOption = $(this).find("option:selected"); + _self.selectNetwork(selectedOption.val()); + }; + + this.update = function() { + //console.log("NetworkPanel:update"); + _self.refreshNetworks(); + _self.retrieveNetworkStatus(false); + } + this.refreshNetworks = function(completeHandler) { + //console.log("NetworkPanel:refreshNetworks"); + _api.scan(function(data) { // completed + //console.log("NetworkPanel:scanned"); + _networks = {}; + var foundCurrentNetwork = false; + // fill network selector + _networkSelector.empty(); + _networkSelector.append( + $("").val(NOT_CONNECTED).html(NOT_CONNECTED) + ); + $.each(data.networks, function(index,element) { + if(element.ssid == _currentNetwork) { + foundCurrentNetwork = true; + } + _networkSelector.append( + $("").val(element.ssid).html(element.ssid) + ); + _networks[element.ssid] = element; + }); + if(foundCurrentNetwork) { + _networkSelector.val(_currentNetwork); + _self.selectNetwork(_currentNetwork); + } + if(completeHandler) completeHandler(); + }/*, + function() { // failed + clearTimeout(_retryRefreshNetworksDelay); + _retryRetrieveStatusDelay = setTimeout(function() { _self.refreshNetworks(completeHandler); },_retryDelay); // retry after delay + }*/); + }; + + this.retrieveNetworkStatus = function(connecting) { + //console.log("NetworkPanel:retrieveNetworkStatus"); + _api.status(function(data) { + if(typeof data.status === 'string') { + data.status = parseInt(data.status); + } + //console.log("NetworkPanel:retrievedStatus status: ",data.status,data.statusMessage); + + // if status changed + if(data.status != _currentNetworkStatus) { + // Determine which network mode ui to show + switch(data.status) { + case NetworkAPI.STATUS.NOT_CONNECTED: + setNetworkMode(NetworkPanel.NETWORK_MODE.NEITHER); + break; + case NetworkAPI.STATUS.CONNECTING_FAILED: + case NetworkAPI.STATUS.CONNECTING: + case NetworkAPI.STATUS.CONNECTED: + setNetworkMode(NetworkPanel.NETWORK_MODE.CLIENT); + break; + case NetworkAPI.STATUS.CREATING: + case NetworkAPI.STATUS.CREATED: + setNetworkMode(NetworkPanel.NETWORK_MODE.ACCESS_POINT); + break; + } + // update info + switch(data.status) { + case NetworkAPI.STATUS.CONNECTED: + _currentNetwork = data.ssid; + _currentLocalIP = data.localip; + _self.selectNetwork(data.ssid); + break; + case NetworkAPI.STATUS.CONNECTING_FAILED: + case NetworkAPI.STATUS.CONNECTING: + _currentLocalIP = ""; + break; + case NetworkAPI.STATUS.CREATING: + case NetworkAPI.STATUS.CREATED: + _currentNetwork = undefined; + _self.selectNetwork(NOT_CONNECTED); + if(data.ssid && data.status == NetworkAPI.STATUS.CREATED) { + _currentAP = data.ssid; + } + break; + } + // update ui + updateClientModeUI(data.status,data.statusMessage); + updateAPModeUI(data.status,""); + } + + // Keep checking for updates? + if(connecting) { + switch(data.status) { + case NetworkAPI.STATUS.CONNECTING: + case NetworkAPI.STATUS.CREATING: + clearTimeout(_retryRetrieveStatusDelay); + _retryRetrieveStatusDelay = setTimeout(function() { _self.retrieveNetworkStatus(connecting); },_retryRetrieveStatusDelayTime); // retry after delay + break; + } + } + _currentNetworkStatus = data.status; + }, function() { + //console.log("NetworkPanel:retrieveStatus failed"); + clearTimeout(_retryRetrieveStatusDelay); + _retryRetrieveStatusDelay = setTimeout(function() { _self.retrieveNetworkStatus(connecting); }, _retryRetrieveStatusDelayTime); // retry after delay + }); + }; + function setNetworkMode(mode) { + //console.log("NetworkPanel:setNetworkMode: ",_networkMode,">",mode); + if(mode == _networkMode) return; + switch(mode) { + case NetworkPanel.NETWORK_MODE.NEITHER: + _apFieldSet.show(); + _clientFieldSet.show(); + break; + case NetworkPanel.NETWORK_MODE.CLIENT: + _clientRadioButton.prop('checked',true); + _apFieldSet.hide(); + _clientFieldSet.show(); + break; + case NetworkPanel.NETWORK_MODE.ACCESS_POINT: + _apRadioButton.prop('checked',true); + _apFieldSet.show(); + _clientFieldSet.hide(); + break; + } + _networkMode = mode; + if(_networkModeChangedHandler) _networkModeChangedHandler(_networkMode); + } + + this.selectNetwork = function(ssid) { + //console.log("NetworkPanel:selectNetwork: ",ssid); + if(ssid == "") return; + _selectedNetwork = ssid; + + var network = _networks[ssid]; + if(network === undefined || network.encryption == "none") { + _passwordLabel.hide(); + _passwordField.hide(); + } else { + _passwordLabel.show(); + _passwordField.show(); + } + _passwordField.val(""); + }; + + function updateClientModeUI(state,statusMessage) { + //console.log("NetworkPanel:updateClientModeUI ",state,statusMessage); + var msg = ""; + switch(state) { + case NetworkAPI.STATUS.NOT_CONNECTED: + case NetworkAPI.STATUS.CREATING: + case NetworkAPI.STATUS.CREATED: + _btnConnect.removeAttr("disabled"); + msg = "Not connected"; + _networkSelector.val(NOT_CONNECTED); + break; + case NetworkAPI.STATUS.CONNECTED: + _btnConnect.removeAttr("disabled"); + msg = "Connected to: "+_currentNetwork+"."; + if(_currentLocalIP != undefined && _currentLocalIP != "") { + var a = ""+_currentLocalIP+""; + msg += " (IP: "+a+")"; + } + _networkSelector.val(_currentNetwork); + break; + case NetworkAPI.STATUS.CONNECTING: + _btnConnect.attr("disabled", true); + msg = "Connecting... Reconnect by connecting your device to "+_selectedNetwork+" and going to connect.doodle3d.com"; + break; + case NetworkAPI.STATUS.CONNECTING_FAILED: + _btnConnect.removeAttr("disabled"); + msg = statusMessage; + break; + } + //console.log(" client display msg: ",msg); + _clientStateDisplay.html(msg); + }; + function updateAPModeUI(state,statusMessage) { + var msg = ""; + switch(state) { + case NetworkAPI.STATUS.CONNECTING_FAILED: + case NetworkAPI.STATUS.NOT_CONNECTED: + case NetworkAPI.STATUS.CONNECTING: + case NetworkAPI.STATUS.CONNECTED: + _btnCreate.removeAttr("disabled"); + msg = "Not currently a access point"; + break; + case NetworkAPI.STATUS.CREATED: + _btnCreate.removeAttr("disabled"); + msg = "Is access point: "+_currentAP+""; + break; + case NetworkAPI.STATUS.CREATING: + _btnCreate.attr("disabled", true); + msg = "Creating access point... Reconnect by connecting your device to "+_substituted_ssid+" and going to draw.doodle3d.com"; + break; + } + //console.log(" ap display msg: ",msg); + _apModeStateDisplay.html(msg); + }; + + this.connectToNetwork = function() { + //console.log("NetworkPanel:connectToNetwork"); + if(_selectedNetwork == undefined) return; + // save network related settings and on complete, connect to network + _form.saveSettings(_form.readForm(),function(validated, data) { + if(!validated) return; + updateClientModeUI(NetworkAPI.STATUS.CONNECTING,""); + _api.associate(_selectedNetwork,_passwordField.val(),true); + + // after switching wifi network or creating a access point we delay the status retrieval + // because the webserver needs time to switch it's status + clearTimeout(_retrieveNetworkStatusDelay); + _retrieveNetworkStatusDelay = setTimeout(function() { _self.retrieveNetworkStatus(true); }, _retrieveNetworkStatusDelayTime); + }); + }; + + this.createAP = function() { + //console.log("createAP"); + // save network related settings and on complete, create access point + _form.saveSettings(_form.readForm(),function(validated, data) { + if(!validated) return; + _substituted_ssid = data.substituted_ssid; + updateAPModeUI(NetworkAPI.STATUS.CREATING,""); + _api.openAP(); + + // after switching wifi network or creating a access point we delay the status retrieval + // because the webserver needs time to switch it's status + clearTimeout(_retrieveNetworkStatusDelay); + _retrieveNetworkStatusDelay = setTimeout(function() { _self.retrieveNetworkStatus(true); }, _retrieveNetworkStatusDelayTime); + }); + }; + + this.setNetworkModeChangedHandler = function(handler) { + _networkModeChangedHandler = handler; + } +} diff --git a/js/settings/PrinterPanel.js b/js/settings/PrinterPanel.js new file mode 100644 index 0000000..16a4620 --- /dev/null +++ b/js/settings/PrinterPanel.js @@ -0,0 +1,59 @@ +/* + * This file is part of the Doodle3D project (http://doodle3d.com). + * + * Copyright (c) 2013, Doodle3D + * This software is licensed under the terms of the GNU GPL v2 or later. + * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. + */ + +function PrinterPanel() { + + this.printerType; + var _api = new PrinterAPI(); + var _form = new FormPanel(); + + // ui elements + var _element; + var _printerSelector; + var _printerSettings; + + var _self = this; + + this.init = function(wifiboxURL,wifiboxCGIBinURL,panelElement) { + + _form.init(wifiboxURL,wifiboxCGIBinURL,panelElement) + _api.init(wifiboxURL,wifiboxCGIBinURL); + _element = panelElement; + _printerSelector = _element.find("#printerType"); + _printerSelector.change(_self.printerSelectorChanged); + + // we use readForm to get all the settings we need to + // reload after changing printer type + _printerSettings = _form.readForm(); + + var gcodePanel = _element.find("#gcodePanel"); + gcodePanel.coolfieldset({collapsed:true}); + } + this.load = function(completeHandler) { + + _api.listAll(function(data) { + $.each(data.printers, function(key, value) { + // console.log(key,value); + $('#printerType').append($('