this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}})});
-
-/*!
- * jQuery UI Touch Punch 0.2.3
- *
- * Copyright 2011–2014, Dave Furfero
- * Dual licensed under the MIT or GPL Version 2 licenses.
- *
- * Depends:
- * jquery.ui.widget.js
- * jquery.ui.mouse.js
- */
-!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.on({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.off({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}($);
diff --git a/src/browser/js/libs/source-map.min.js b/src/browser/js/libs/source-map.min.js
deleted file mode 100644
index 2e9876d8..00000000
--- a/src/browser/js/libs/source-map.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-// source-map
-// Copyright (c) 2009-2011, Mozilla Foundation and contributors
-// All rights reserved.
-!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&r.setSourceContent(n,t)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;d>f;f++){if(n=h[f],e="",n.generatedLine!==a)for(s=0;n.generatedLine!==a;)e+=";",a++;else if(f>0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return 0>e?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),-1===a)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a< =0&&e=n&&r>=e?e-n:e>=t&&o>=e?e-t+l:e>=i&&s>=e?e-i+c:e==a?62:e==u?63:-1}},function(e,n){function r(e,n,r){if(n in e)return e[n];if(3===arguments.length)return r;throw new Error('"'+n+'" is a required argument.')}function t(e){var n=e.match(m);return n?{scheme:n[1],auth:n[2],host:n[3],port:n[4],path:n[5]}:null}function o(e){var n="";return e.scheme&&(n+=e.scheme+":"),n+="//",e.auth&&(n+=e.auth+"@"),e.host&&(n+=e.host),e.port&&(n+=":"+e.port),e.path&&(n+=e.path),n}function i(e){var r=e,i=t(e);if(i){if(!i.path)return e;r=i.path}for(var s,a=n.isAbsolute(r),u=r.split(/\/+/),l=0,c=u.length-1;c>=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(_))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(0>t)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(9>n)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=e.source-n.source;return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:e.name-n.name))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=e.source-n.source,0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:e.name-n.name))))}function f(e,n){return e===n?0:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}n.getArg=r;var m=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,_=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(m)},n.relative=a;var v=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=v?u:l,n.fromSetString=v?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d},function(e,n,r){function t(){this._array=[],this._set=Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;i>o;o++)r.add(e[o],n);return r},t.prototype.size=function(){return Object.getOwnPropertyNames(this._set).length},t.prototype.add=function(e,n){var r=o.toSetString(e),t=i.call(this._set,r),s=this._array.length;(!t||n)&&this._array.push(e),t||(this._set[r]=s)},t.prototype.has=function(e){var n=o.toSetString(e);return i.call(this._set,n)},t.prototype.indexOf=function(e){var n=o.toSetString(e);if(i.call(this._set,n))return this._set[n];throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e){var n=e;return"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=n.sections?new s(n):new o(n)}function o(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=a.getArg(n,"version"),t=a.getArg(n,"sources"),o=a.getArg(n,"names",[]),i=a.getArg(n,"sourceRoot",null),s=a.getArg(n,"sourcesContent",null),u=a.getArg(n,"mappings"),c=a.getArg(n,"file",null);if(r!=this._version)throw new Error("Unsupported version: "+r);t=t.map(String).map(a.normalize).map(function(e){return i&&a.isAbsolute(i)&&a.isAbsolute(e)?a.relative(i,e):e}),this._names=l.fromArray(o.map(String),!0),this._sources=l.fromArray(t,!0),this.sourceRoot=i,this.sourcesContent=s,this._mappings=u,this.file=c}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=a.getArg(n,"version"),o=a.getArg(n,"sections");if(r!=this._version)throw new Error("Unsupported version: "+r);this._sources=new l,this._names=new l;var i={line:-1,column:0};this._sections=o.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var n=a.getArg(e,"offset"),r=a.getArg(n,"line"),o=a.getArg(n,"column");if(r=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.fromSourceMap=function(e){var n=Object.create(o.prototype),r=n._names=l.fromArray(e._names.toArray(),!0),t=n._sources=l.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file;for(var s=e._mappings.toArray().slice(),u=n.__generatedMappings=[],c=n.__originalMappings=[],p=0,h=s.length;h>p;p++){var f=s[p],d=new i;d.generatedLine=f.generatedLine,d.generatedColumn=f.generatedColumn,f.source&&(d.source=t.indexOf(f.source),d.originalLine=f.originalLine,d.originalColumn=f.originalColumn,f.name&&(d.name=r.indexOf(f.name)),c.push(d)),u.push(d)}return g(n.__originalMappings,a.compareByOriginalPositions),n},o.prototype._version=3,Object.defineProperty(o.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?a.join(this.sourceRoot,e):e},this)}}),o.prototype._parseMappings=function(e,n){for(var r,t,o,s,u,l=1,p=0,h=0,f=0,d=0,m=0,_=e.length,v=0,C={},y={},A=[],S=[];_>v;)if(";"===e.charAt(v))l++,v++,p=0;else if(","===e.charAt(v))v++;else{for(r=new i,r.generatedLine=l,s=v;_>s&&!this._charIsMappingSeparator(e,s);s++);if(t=e.slice(v,s),o=C[t])v+=t.length;else{for(o=[];s>v;)c.decode(e,v,y),u=y.value,v=y.rest,o.push(u);if(2===o.length)throw new Error("Found a source, but no line and column");if(3===o.length)throw new Error("Found a source and line, but no column");C[t]=o}r.generatedColumn=p+o[0],p=r.generatedColumn,o.length>1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),S.push(r),"number"==typeof r.originalLine&&A.push(r)}g(S,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=S,g(A,a.compareByOriginalPositions),this.__originalMappings=A},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),null!=this.sourceRoot&&(i=a.join(this.sourceRoot,i)));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}):!1},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=a.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var r;if(null!=this.sourceRoot&&(r=a.urlParse(this.sourceRoot))){var t=e.replace(/^file:\/\//,"");if("file"==r.scheme&&this._sources.has(t))return this.sourcesContent[this._sources.indexOf(t)];if((!r.path||"/"==r.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(n)return null;throw new Error('"'+e+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),!this._sources.has(n))return{line:null,column:null,lastColumn:null};n=this._sources.indexOf(n);var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:0>e?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(0>s)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(s>i){var a=t(i,s),u=i-1;r(e,a,s);for(var l=e[s],c=i;s>c;c++)n(e[c],l)<=0&&(u+=1,r(e,u,c));r(e,u+1,c);var g=u+1;o(e,n,i,g-1),o(e,n,g+1,s)}}n.quickSort=function(e,n){o(e,n,0,e.length-1)}},function(e,n,r){function t(e,n,r,t,o){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==n?null:n,this.source=null==r?null:r,this.name=null==o?null:o,this[u]=!0,null!=t&&this.add(t)}var o=r(1).SourceMapGenerator,i=r(4),s=/(\r?\n)/,a=10,u="$$$isSourceNode$$$";t.fromStringWithSourceMap=function(e,n,r){function o(e,n){if(null===e||void 0===e.source)a.add(n);else{var o=r?i.join(r,e.source):e.source;a.add(new t(e.originalLine,e.originalColumn,o,n,e.name))}}var a=new t,u=e.split(s),l=function(){var e=u.shift(),n=u.shift()||"";return e+n},c=1,g=0,p=null;return n.eachMapping(function(e){if(null!==p){if(!(c0&&(p&&o(p,l()),a.add(u.join(""))),n.sources.forEach(function(e){var t=n.sourceContentFor(e);null!=t&&(null!=r&&(e=i.join(r,e)),a.setSourceContent(e,t))}),a},t.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},t.prototype.prepend=function(e){if(Array.isArray(e))for(var n=e.length-1;n>=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;t>r;r++)n=this.children[r],n[u]?n.walk(e):""!==n&&e(n,{source:this.source,line:this.line,column:this.column,name:this.name})},t.prototype.join=function(e){var n,r,t=this.children.length;if(t>0){for(n=[],r=0;t-1>r;r++)n.push(this.children[r]),n.push(e);n.push(this.children[r]),this.children=n}return this},t.prototype.replaceRight=function(e,n){var r=this.children[this.children.length-1];return r[u]?r.replaceRight(e,n):"string"==typeof r?this.children[this.children.length-1]=r.replace(e,n):this.children.push("".replace(e,n)),this},t.prototype.setSourceContent=function(e,n){this.sourceContents[i.toSetString(e)]=n},t.prototype.walkSourceContents=function(e){for(var n=0,r=this.children.length;r>n;n++)this.children[n][u]&&this.children[n].walkSourceContents(e);for(var t=Object.keys(this.sourceContents),n=0,r=t.length;r>n;n++)e(i.fromSetString(t[n]),this.sourceContents[t[n]])},t.prototype.toString=function(){var e="";return this.walk(function(n){e+=n}),e},t.prototype.toStringWithSourceMap=function(e){var n={code:"",line:1,column:0},r=new o(e),t=!1,i=null,s=null,u=null,l=null;return this.walk(function(e,o){n.code+=e,null!==o.source&&null!==o.line&&null!==o.column?((i!==o.source||s!==o.line||u!==o.column||l!==o.name)&&r.addMapping({source:o.source,original:{line:o.line,column:o.column},generated:{line:n.line,column:n.column},name:o.name}),i=o.source,s=o.line,u=o.column,l=o.name,t=!0):t&&(r.addMapping({generated:{line:n.line,column:n.column}}),i=null,t=!1);for(var c=0,g=e.length;g>c;c++)e.charCodeAt(c)===a?(n.line++,n.column=0,c+1===g?(i=null,t=!1):t&&r.addMapping({source:o.source,original:{line:o.line,column:o.column},generated:{line:n.line,column:n.column},name:o.name})):n.column++}),this.walkSourceContents(function(e,n){r.setSourceContent(e,n)}),{code:n.code,map:r}},n.SourceNode=t}])});
diff --git a/src/browser/scss/_editor.scss b/src/browser/scss/_editor.scss
deleted file mode 100644
index 46b79da6..00000000
--- a/src/browser/scss/_editor.scss
+++ /dev/null
@@ -1,417 +0,0 @@
-#editor {
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- background: var(--color-fg);
- padding: 1rem 8rem 8rem;
- margin-top: 2rem;
- flex-shrink:0;
- &:empty {
- padding:0;
- margin: 0;
- }
- ul {
- padding: 4rem;
- list-style:none;
- li {
- margin-bottom: 4rem;
- position: relative;
- &:last-child {
- margin: 0;
- }
- }
- }
- .btn + span {
- position: absolute;
- right:0rem;
- top:0rem;
- padding:8rem;
- opacity: 0.6;
- cursor: pointer;
- &:hover {
- opacity: 1;
- }
- }
-
- .form {
- margin-top: 10rem;
- }
-}
-.form {
- line-height: 18rem;
- .input-wrapper {
- display: flex;
- // margin-bottom:4rem;
- margin-top: -1rem;
- // box-shadow: 0 0 0 1 var(--color-bg);
- background:var(--color-bg);
- align-items: stretch;
- z-index: 1;
- border-bottom: 1rem solid var(--color-bg);
- position: relative;
- justify-content: center;
- text-transform: none;
- font-weight: 500;
-
- &:last-child {
- margin-bottom:0;
- }
- label {
- background: var(--color-fg);
- flex-shrink: 0;
- padding: 6rem 7rem 4rem;
- // border:1rem solid var(--color-bg);
- // border-bottom: 1rem solid var(--color-bg);
- min-width: 29%;
- box-shadow: 1rem 0 0 0 var(--color-bg) inset;
- margin-top: 1rem;
- }
- .input {
- background: var(--color-bg);
- flex: 1 1 100%;
- padding:5rem;
- border-top:1rem solid var(--color-fg);
- border-radius: 0;
- -webkit-appearance:none;
- cursor: text;
- }
- &.column {
- ul {
- padding: 1rem 2rem!important;
- overflow: auto;
- li:not(:last-child) {
- margin-bottom: 2rem!important;
- }
- .sortable-placeholder {
- background: transparent;
- &:after {
- content:"|";
- color: transparent;
- }
- }
- }
- }
- .checkbox {
- line-height: 18rem;
- height: 18rem;
- width: 18rem;
- position: absolute;
- right:5rem;
- top:50%;
- margin-top: -9rem;
- cursor: pointer;
- background: var(--color-fg);
- text-align: center;
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- display: flex;
- align-items: center;
- justify-content: center;
- i {
- color: transparent;
- }
- &.on i {
- color:var(--color-accent);
- }
- }
- }
- label {
- display: block;
- font-size: 10rem;
- // background: var(--color-track);
- }
- .info {
- color:var(--color-text-fade);
- margin-bottom:10rem;
- }
- .input {
- display:block;
- border:0;
- font:inherit;
- color:var(--color-text);
- width:auto;
- .btn {
- background: var(--color-raised);
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 0 0 1rem var(--color-bg);
- &:not(:last-child){
- cursor: -webkit-grab;
- cursor: grab;
- }
- }
- }
- textarea {
- display:block;
- border:0;
- font:inherit;
- background: none;
- color:var(--color-text);
- width:100%;
- padding:5rem;
- overflow-y: hidden;
- overflow-x: auto;
- white-space: nowrap;
- border-top:1rem solid var(--color-fg);
- resize: none;
- font-size: 12rem!important;
- }
- .error label{
- border-right: 1rem solid rgba(red, .75);
- }
- .select-wrapper {
- position: relative;
- margin: 2rem;
- flex: 1 1 100%;
- &:after{
- content:"\f107";
- font-family: FontAwesome;
- position: absolute;
- padding:5rem;
- right:0;
- top:0;
- font-size: 20rem;
- pointer-events: none;
- }
-
- .input {
- border:0;
- width: 100%;
- cursor: pointer;
- background: var(--color-fg);
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- }
- }
- select {
- -webkit-appearance:none;
- -moz-appearance:none;
- appearance:none;
- font-size: 12rem!important;
- }
- .submit {
- margin-top:30rem;
- }
- .separator {
- line-height: 30rem;
- height: 30rem;
- margin-top: 10rem;
- position: relative;
- display: flex;
- align-items: center;
- border: 1rem solid var(--color-bg);
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- span {
- text-transform: lowercase;
- font-variant: small-caps;
- position: relative;
- display: block;
- width:100%;
- text-align:center;
- }
- }
- .separator + .input-wrapper .input {
- border-top-color:transparent;
- }
-}
-
-
-
-.widget.editing {
- z-index: 11!important;
- // overflow: visible;
-}
-.widget.editing:after, li.editing a:before, a.editing:before, .content.editing:before, #container.editing:before{
- content:"";
- z-index: 999;
- position: absolute;
- top:0;
- left:0;
- right:0;
- bottom:0;
- border:1rem dashed var(--color-accent);
- pointer-events: none;
- box-shadow: none!important;
- opacity: 1!important;
-}
-.widget.editing:after {
- // right:-1rem;
- // bottom:-1rem;
-}
-
-.context-menu {
- position:fixed;
- z-index: 999999999;
- background: var(--color-raised);
- box-shadow: 0 0 4rem 1rem var(--color-bg);
- text-transform: none;
- .item {
- color:var(--color-text)
- }
- .context-menu {
- position: absolute;
- left:100%;
- top:0;
- opacity:0;
- pointer-events: none;
- margin-left: 2rem;
- &:before {
- content:"";
- position: absolute;
- top:0;
- bottom:0;
- left:-2rem;
- width:2rem;
- }
- }
- > .item {
- padding: 10rem 15rem 10rem 10rem;
- position:relative;
- cursor: pointer;
- i {
- margin-right:5rem;
- width: 15rem;
- text-align: center;
- }
- &:hover, &:focus {
- > .context-menu {
- pointer-events: auto;
- opacity: 1;
- }
- &:after {
- content:"";
- position: absolute;
- left:0;
- top:0;
- width: 100%;
- height:100%;
- background:var(--color-accent);
- opacity: 0.5;
- z-index: -1;
- }
- }
- &.has-sub:before {
- content:"\f105";
- display: block;
- font-family: FontAwesome;
- float:right;
- margin-right:-10rem;
- padding-left: 10rem;
- }
- }
-}
-
-.ui-resizable-handle {
- position: absolute;
- z-index: 1000000;
- display: flex;
- justify-content: center;
- align-items: center;
- background: var(--color-accent);
- width:10rem;
- height:10rem;
-
- &:after {
- content:"";
- position: absolute;
- }
- &.ui-resizable-se {
- content:"";
- bottom: 0;
- right: 0;
- cursor: se-resize;
- &:after {
- top:-5rem;
- right:0;
- left:-5rem;
- bottom:0em;
- }
- }
- &.ui-resizable-e {
- top: 50%;
- margin-top:-5rem;
- right: 0;
- cursor: e-resize;
- &:after {
- top:-5rem;
- right:0;
- left:-5rem;
- bottom:-5rem;
- }
- }
- &.ui-resizable-s {
- bottom: 0;
- left: 50%;
- margin-left:-5rem;
- cursor: s-resize;
- &:after {
- top:-5rem;
- right:-5rem;
- left:-5rem;
- bottom:0em;
- }
- }
-}
-
-.ui-helper {
- z-index: 12!important;
- opacity: 1!important;
- &:before {
- content:"";
- position: absolute;
- top:1rem;
- left:1rem;
- right:0;
- bottom:0;
- border:1rem dashed var(--color-accent);
- }
- &:after {
- content:"";
- position: absolute;
- top:1rem;
- left:1rem;
- right:0;
- bottom:0;
- background: var(--color-accent);
- opacity: .25;
- }
-}
-
-.ui-draggable-handle:not(.label) {
- position: absolute;
- top: 0;
- left: 0;
- z-index: 100000;
- height:10rem;
- width: 10rem;
- display: flex;
- justify-content: center;
- align-items: center;
- background: var(--color-accent);
- &:after {
- content:"";
- position: absolute;
- top:0;
- right:-5rem;
- left:0;
- bottom:-5rem;
- }
-}
-
-.ui-draggable-handle {
- cursor: -webkit-grab;
- &:active {
- cursor:-webkit-grabbing;
- }
-}
-
-// GRID
-
-.editor-enabled {
- &:not(.no-grid) {
- .tab:not(.has-tabs), .panel {
- background-image: linear-gradient(to bottom, var(--color-grid) 1rem, transparent 1rem),
- linear-gradient(to right, var(--color-grid) 1rem, transparent 1rem);
- --size: calc(var(--grid-width) * 1rem);
- background-size: var(--size) var(--size);
- background-attachment: local;
- background-position: 0 0;
- }
- }
-
-}
diff --git a/src/browser/scss/_layout.scss b/src/browser/scss/_layout.scss
deleted file mode 100644
index eeec0202..00000000
--- a/src/browser/scss/_layout.scss
+++ /dev/null
@@ -1,128 +0,0 @@
-body {
- background:var(--color-bg);
-}
-
-#container {
- position: absolute;
- top:0;
- left:0;
- bottom:0;
- right:0;
- display:flex;
- flex-direction: column;
- background:var(--color-bg);
- padding:2rem;
- &.sidepanel-open {
- right:var(--sidepanel-size);
- }
-}
-
-
-.navigation {
- height:var(--nav-height);
- margin-bottom: 1rem;
- margin-left: 1rem;
- flex-shrink:0;
- // font-weight:bold;
- text-transform: uppercase;
- background: transparent;
- height:calc(var(--nav-height) - 2rem);
-
- &:after {
- background: var(--color-bg);
- }
- a.on {
- border-color: var(--color-bg);
- }
-
- &.main {
- li:last-child {
- width:var(--nav-height);
- max-width:var(--nav-height);
- min-width:var(--nav-height);
- i {
- margin:0 auto;
- }
- }
- }
- ul {
- list-style:none;
- display: flex;
- overflow: hidden;
- height:100%;
-
- li {
- display:block;
- min-width:0;
- flex: 1 1 100%;
- cursor:pointer;
- height:100%;
- margin-right: 1rem;
-
-
- &:last-child {
- margin-right:0;
- margin-left: auto;
- i {
- font-size: 14rem;
- }
- }
- a {
- background: var(--color-raised);
- pointer-events: none;
- padding: 5rem;
- height:100%;
- display: flex;
- align-items: center;
- overflow:hidden;
- text-align:center;
- position:relative;
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- letter-spacing: 1rem;
- font-size: 109%;
- span {
- display:block;
- width:100%;
- -webkit-mask: linear-gradient(to left, rgba(0, 0, 0, 0), #000000 10rem) no-repeat;
- }
-
- }
- #open-toggle {
- pointer-events: auto;
- i {
- pointer-events: none;
- }
- }
- &.on a, .sidepanel-open {
- position: relative;
- z-index: 0;
- // background:var(--color-fg);
- color: var(--color-custom);
- &:after {
- content: "";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.4;
- background: radial-gradient( ellipse at center, transparent, var(--color-bg));
- }
- &:before {
- content:"";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.3;
- box-shadow: 0 0 0 1rem var(--color-custom) inset;
- border-radius: inherit;
- }
- }
- }
- .parent + li a {
- padding-left: calc(5rem + 0.5 * var(--nav-height));
- }
- }
-}
diff --git a/src/browser/scss/_scrollbars.scss b/src/browser/scss/_scrollbars.scss
deleted file mode 100644
index d92f4603..00000000
--- a/src/browser/scss/_scrollbars.scss
+++ /dev/null
@@ -1,88 +0,0 @@
-
-::-webkit-scrollbar {
- width: var(--scrollbar-size);
- height:var(--scrollbar-size);
- opacity:1;
-
-}
-
-::-webkit-scrollbar-track-piece {
- background: var(--color-bg);
- &:vertical {
- border-left:2rem solid var(--color-bg);
- }
- &:horizontal {
- border-top:2rem solid var(--color-bg);
- }
-}
-::-webkit-scrollbar-corner {
- background: var(--color-fg);
- border-left:2rem solid var(--color-bg);
- border-top:2rem solid var(--color-bg);
-}
-::-webkit-scrollbar-thumb {
- background: var(--color-raised);
-
- &:vertical {
- border-left:2rem solid var(--color-bg);
- }
- &:horizontal {
- border-top:2rem solid var(--color-bg);
- }
-}
-
-
-@mixin arrow($r) {
- background-image:url('data:image/svg+xml;utf8, ');
- background-blend-mode: difference, normal;
-}
-
-::-webkit-scrollbar-button:decrement:start, ::-webkit-scrollbar-button:increment:end {
-
- background:var(--color-fg);
- height:var(--scrollbar-size);
- width: var(--scrollbar-size);
-
- display: block;
- color:red;
-
- background-size:contain;
- background-position: center;
-
- &:vertical {
- &:decrement:start {
- border-left:2rem solid var(--color-bg);
- border-bottom:1rem solid var(--color-bg);
- @include arrow(180)
- }
-
- &:increment:end {
- border-left:2rem solid var(--color-bg);
- border-top:1rem solid var(--color-bg);
- @include arrow(0)
- }
- }
- &:horizontal {
- &:decrement:start {
- border-right:1rem solid var(--color-bg);
- border-top:2rem solid var(--color-bg);
- @include arrow(90)
- }
-
- &:increment:end {
- border-left:1rem solid var(--color-bg);
- border-top:2rem solid var(--color-bg);
- @include arrow(-90)
- }
- }
-
-}
-
-// ::-webkit-resizer {
-// border-left:2rem solid var(--color-bg);
-// border-top:2rem solid var(--color-bg);
-// background:var(--color-fg);
-// background-size:contain;
-// background-position: 2rem 2rem;
-// @include arrow(-45)
-// }
diff --git a/src/browser/scss/_sidepanel.scss b/src/browser/scss/_sidepanel.scss
deleted file mode 100644
index e3515ed9..00000000
--- a/src/browser/scss/_sidepanel.scss
+++ /dev/null
@@ -1,126 +0,0 @@
-
-#sidepanel {
- position:absolute;
- z-index: 999999;
- width:var(--sidepanel-size);
- border-top: 2rem solid var(--color-bg);
- border-bottom: 2rem solid var(--color-bg);
- border-right: 2rem solid var(--color-bg);
- top:0;
- right:0;
- bottom:0;
- margin-right:calc(-1 * var(--sidepanel-size));
- background:var(--color-bg);
- transition:transform .25s, opacity .25s;
- transform: translate3d(0,0,0);
- opacity: 0;
- overflow-y: auto;
- overflow-x: visible;
- box-shadow: 0 0 15rem 0 var(--color-bg), 0 0 0 2rem var(--color-bg);
- display: flex;
- flex-direction: column;
-
- &.sidepanel-open {
- transform: translate3d(calc(-1 * var(--sidepanel-size)),0,0);
- opacity: 1;
- }
-
- .navigation {
- margin-bottom:2rem;
- margin-left: 0;
- li {
- cursor:default;
- }
- a {
- text-transform: none;
- color: var(--color-accent);
- justify-content: center;
- }
- }
-
- #options {
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- background: var(--color-fg);
- padding: 8rem;
- flex: 1 1 auto;
- flex-shrink:0;
-
- li {
- display: block;
- margin-bottom: 8rem;
- &:last-child {
- margin-bottom:0;
- }
- }
- }
-
-}
-.actions {
- padding:0.5rem;
- background:var(--color-bg);
- display: flex;
- align-items: stretch;
- flex-wrap:wrap;
- .title {
- flex: 1 1 100%;
- background: var(--color-fg);
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- padding: 13rem 10rem;
- position: relative;
- margin: 0.5rem;
- &.disabled {
- color:var(--color-text-fade);
- }
- &:before {
- content:"";
- position: absolute;
- top:0;
- left:0;
- right:0;
- bottom:0;
- box-shadow: 0 0 0 1rem;
- color:var(--color-bg);
- }
-
- }
- a {
- flex: 4 1 32%;
- padding:13rem 10rem;
- display: block;
- text-align: center;
- position: relative;
- color:var(--color-text);
- overflow: visible;
- margin: 0.5rem;
-
- &.on {
- z-index: 0;
- color: var(--color-custom);
- &:not(.fullscreenToggle) {
- pointer-events: none;
- }
- &:after {
- content: "";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.4;
- background: radial-gradient( ellipse at center, transparent, var(--color-bg));
- }
- &:before {
- content:"";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.3;
- box-shadow: 0 0 0 1rem var(--color-custom) inset;
- border-radius: inherit;
- }
- }
-
- }
-}
diff --git a/src/browser/scss/_vars.scss b/src/browser/scss/_vars.scss
deleted file mode 100644
index 991cd749..00000000
--- a/src/browser/scss/_vars.scss
+++ /dev/null
@@ -1,31 +0,0 @@
-:root {
-
- ////////////////////// COLOR SCHEME
-
- --color-text:rgba(255, 255, 255, .6);
- --color-text-fade:rgba(255, 255, 255, .4);
-
- --color-accent:rgba(82, 168, 255, 1);
- --color-grid: rgba(82, 168, 255, .1);
-
- --color-bg: rgb(25, 31, 42);
- --color-track: rgb(32, 41, 58);
- --color-fg: rgb(40, 49, 67);
- --color-raised: rgb(49, 63, 85);
-
- --color-light:rgba(255, 255, 255, .06);
-
- --color-white: white;
-
- ////////////////////// AUTO
-
- --color-custom:var(--color-accent);
-
- ////////////////////// MISC
-
- --nav-height:40rem;
- --sidepanel-size:300rem;
- --scrollbar-size:20rem;
-
- --grid-width:10;
-}
diff --git a/src/browser/scss/_widgets.scss b/src/browser/scss/_widgets.scss
deleted file mode 100644
index c0906e63..00000000
--- a/src/browser/scss/_widgets.scss
+++ /dev/null
@@ -1,82 +0,0 @@
-
-.widget {
- display:inline-block;
- height:auto;
- overflow: hidden;
- position:relative;
- vertical-align:top;
- box-shadow: 1rem 0 0 0 var(--color-border),
- 0 1rem 0 0 var(--color-border),
- 1rem 1rem 0 0 var(--color-border),
- 0 0 0 1rem var(--color-light) inset;
- border-left:1rem solid var(--color-border);
- border-top:1rem solid var(--color-border);
- -webkit-tap-highlight-color:transparent;
- display: inline-flex;
- flex-direction: column;
- --default-bg: var(--color-fg);
- background: var(--default-bg);
- max-width: 100%;
- max-height: 100%;
- text-transform: uppercase;
- contain: style size layout;
- color: var(--color-text);
-
- &.absolute-position {
- position: absolute;
- z-index: 10;
- }
-
- &.nolabel {
- > .label {
- display:none;
- }
- }
-
- > .label + div {
- border-top-left-radius:0;
- border-top-right-radius:0;
- border-bottom-right-radius:inherit;
- border-bottom-left-radius:inherit;
- }
- &.nolabel > .label + div {
- border-radius: inherit;
- }
-
- .label {
- text-overflow:ellipsis;
- overflow:hidden;
- text-align:center;
- height:30rem;
- max-height:30rem;
- padding:0 6rem;
- width: 100%;
- flex-shrink: 0;
- display: flex;
- justify-content: space-around;
- align-items: center;
- &.accent {
- color:var(--color-accent);
- }
- }
-}
-
-
-@import 'widgets/fader';
-@import 'widgets/knob';
-
-@import 'widgets/matrices';
-@import 'widgets/pads';
-
-@import 'widgets/plots';
-
-
-@import 'widgets/toggle';
-@import 'widgets/push';
-@import 'widgets/switch';
-
-@import 'widgets/panel';
-
-@import 'widgets/inputs';
-
-@import 'widgets/maths';
diff --git a/src/browser/scss/style.scss b/src/browser/scss/style.scss
deleted file mode 100644
index b96a3287..00000000
--- a/src/browser/scss/style.scss
+++ /dev/null
@@ -1,551 +0,0 @@
-@import 'vars';
-@import 'reset';
-
-
-@import 'scrollbars';
-
-@import 'layout';
-
-@import 'editor';
-@import 'sidepanel';
-@import 'widgets';
-
-
-input:focus::selection{
- background:var(--color-accent);
- color:var(--color-text);
-}
-input {
- cursor: text;
-}
-
-
-
-
-
-
-html, body {
- height:100%;
- overflow:hidden;
- position:relative;
-
-}
-
-html{
- // global pixel scaling
- font-size: 1px;
-
- // prevent android's auto font-resize
- max-height: 999999px;
-}
-
-body {
- color: var(--color-text);
- white-space:nowrap;
- opacity:1;
- cursor: default;
- font-family: 'Roboto', sans-serif;
- font-size:11rem;
- line-height:100%;
- font-weight: 500;
- text-transform: uppercase;
- letter-spacing: 1rem;
-}
-
-.btn {
- background: var(--color-raised);
- display: block;
- padding:15rem;
- position: relative;
- white-space: nowrap;
- text-overflow: ellipsis;
- overflow: hidden;
- cursor: pointer;
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- &.small {
- padding:8rem;
- padding-right: 15rem;
- }
- &.tiny {
- padding:6rem;
- }
- &.warning {
- background:firebrick;
- }
- &.disabled {
- pointer-events: none;
- color:var(--color-text-fade);
- }
- &.align-center {
- text-align: center
- }
-}
-
-
-
-
-
-
-
-
-
-
-#lobby {
- background: var(--color-bg);
- position: absolute;
- top:0;
- left:0;
- right: 0;
- bottom:0;
- z-index: 2;
- display: flex;
- align-items: center;
- justify-content: center;
- overflow-y: auto;
- padding:20rem;
-
- .main {
- width:600rem;
- max-width: 100%;
- max-height:100%;
- display: flex;
- flex-direction: column;
- opacity: 0;
- transition: opacity .25s;
- &.loaded {
- opacity: 1;
- overflow: auto;
- }
- }
- .list {
- overflow: auto;
- background: var(--color-fg);
- border-top:2rem solid var(--color-bg);
- text-transform: none;
- font-weight: 500;
- flex: 1 1 auto;
- a {
- &:focus {
- &:after {
- content:"";
- position: absolute;
- top:0;
- left:0;
- bottom:0;
- right:0;
- border:1rem solid var(--color-accent);
- opacity: 0.3;
- }
- }
- }
- }
- .header {
- padding:22rem 20rem 20rem;
- white-space: nowrap;
- text-overflow: ellipsis;
- flex-grow: 0;
- background-color: var(--color-fg);
- color:var(--color-accent);
- letter-spacing: 1rem;
- font-size: 12rem;
- background:var(--color-raised);
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- }
- .footer {
- background: var(--color-fg);
- white-space: nowrap;
- text-overflow: ellipsis;
- flex-grow: 0;
- border-top:2rem solid var(--color-bg);
- a {
- background:var(--color-raised);
- &:focus {
- &:after {
- content:"";
- position: absolute;
- top:0;
- left:0;
- bottom:0;
- right:0;
- border:1rem solid var(--color-accent);
- opacity: 0.3;
- }
- }
- }
- }
- a {
- display: block;
- overflow: hidden;
- padding:17rem;
- padding-right:39rem;
- position: relative;
- white-space: nowrap;
- text-overflow: ellipsis;
- background: none;
- border-bottom:1rem solid var(--color-bg);
-
- &:last-child {
- border-bottom:0;
- }
- span {
- position: absolute;
- right:0rem;
- top:0rem;
- padding:17rem;
- color:var(--color-text-fader);
- z-index: 1;
- &:hover {
- color:var(--color-accent);
- }
- }
- }
-}
-
-
-#launcher {
- background: var(--color-fg);
- padding:14rem;
- display: flex;
- flex-direction: column;
- .form {
- width: 100%;
- background: var(--color-fg);
- overflow: hidden;
- opacity: 0;
- transition: opacity .25s;
- &.loaded {
- opacity: 1;
- overflow: auto;
- }
- }
- .item-wrapper {
- // margin-bottom:4rem;
- label {
- min-width:98rem;
- }
- .input-wrapper {
- position: relative;
- // height: 28rem;
- // overflow: hidden;
- // margin: 0;
- box-shadow: none;
-
- .clear {
- padding:0;
- height:26rem;
- width: 26rem;
- line-height: 26rem;
- text-align: center;
- position: absolute;
- right:1rem;
- top:2rem;
- background: none;
- opacity: .7;
- box-shadow: none;
- }
- input {
- padding-right:35rem;
- box-shadow: none;
- }
- input[value="true"] {
- color: inherit;
- }
- input[disabled] {
- color:var(--color-accent);
- }
- .checkbox {
- right: 30rem;
- &.disabled {
- pointer-events: none;
- &.on i {
- color:var(--color-text-fade);
- }
- }
- }
- }
- .error-msg, .restart-msg {
- transition: height .25s;
- height: 0rem;
- white-space:normal;
- padding: 0 4rem;
- margin-left:1rem;
- text-transform: none;
- }
- &.error, &.restart {
- .error-msg {
- height: 28rem;
- line-height: 28rem;
- background: rgba(red,0.25)
- }
- .restart-msg {
- height: 28rem;
- line-height: 28rem;
- background: rgba(orange,0.25)
- }
- }
- }
- .header {
- background: var(--color-fg);
- border: 1rem solid var(--color-bg);
- margin-bottom: -1rem;
- color: var(--color-accent);
- cursor: default;
- z-index: 2;
- box-shadow: none;
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- padding: 16rem 15rem 14rem;
-
- #title {
- text-transform: uppercase;
- letter-spacing: 1rem;
- font-size: 12rem;
- line-height: 12rem;
- }
-
- #version {
- opacity: .5;
- text-transform: none;
- }
-
-
- #new-version {
- color:yellow;
- cursor: pointer;
- float:right;
- }
- }
- .start {
- border: 1rem solid var(--color-bg);
- z-index: 1;
- margin-top: 5rem;
- &:after {
- content:"";
- position: absolute;
- top:0;
- left:0;
- right: 0;
- bottom:0;
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- pointer-events: none;
- }
- &.disabled {
- opacity: .5;
- }
- &.started {
- color:#fff;
- cursor: default;
- a {
- cursor: pointer;
- text-decoration: underline;
- }
- }
- &.started:before {
- content:"";
- position: absolute;
- top:0;
- left:0;
- right:0;
- bottom:0;
- background-color: var(--color-accent);
- opacity: 0.25;
- z-index: -1;
- }
- }
- .save {
- float:left;
- width:90rem;
- border-right: 0;
- &:before {
- transition: opacity .5s;
- content:"";
- position: absolute;
- top:0;
- left:0;
- right:0;
- bottom:0;
- background-color: var(--color-accent);
- opacity: 0;
- z-index: -1;
- }
- &.saved:before {
- transition: none;
- opacity: 0.25;
-
- }
- }
-
- .terminal {
- margin-top: 5rem;
- background: var(--color-bg);
- font-family: monospace;
- text-transform: none;
- padding:3rem;
- border:2rem solid var(--color-bg);
- letter-spacing: normal;
- cursor: auto;
- flex:1;
- height: 100%;
- overflow: hidden;
- overflow-y: scroll;
- height: 50rem;
- &::-webkit-scrollbar-button:decrement:start, &::-webkit-scrollbar-button:increment:end {
- display:none;
- }
- &::-webkit-scrollbar {
- width: 8rem;
- }
- div {
- user-select:text;
- width: 100%;
- white-space: pre-line;
- word-wrap: break-word;
- text-indent: -10px;
- padding-left: 10px;
- margin-top: 4rem;
- }
- .log {
- }
- .error {
- color: rgba(255, 150, 50, 1)
- }
- }
-}
-
-
-
-
-
-
-
-
-
-
-#loading {
- position: fixed;
- top:50%;
- left:50%;
- margin-left:-15rem;
- margin-top:-15rem;
- text-align: center;
-}
-
-.spinner {
- display: block;
- margin: 0 auto;
- height:36rem;
- width:36rem;
- border-radius: 50%;
- border:5rem solid var(--color-light);
- position: relative;
-
- &:before {
- content:"";
- position: absolute;
- left:-4rem;
- top:-4rem;
- right:-4rem;
- bottom:-4rem;
- border:4rem solid var(--color-bg);
- border-radius: 50%;
- }
- &:after {
- content:"";
- position: absolute;
- left:-3rem;
- top:-3rem;
- right:-3rem;
- bottom:-3rem;
- border:2rem solid var(--color-track);
- border-top:2rem solid var(--color-accent);
- transform: rotateZ(0deg);
- animation: spin .5s linear infinite;
- border-radius: 50%;
- }
-}
-
-@keyframes spin {
- 0% {transform: rotateZ(0deg);}
- 100% {transform: rotateZ(360deg);}
-}
-
-
-
-
-
-
-.popup {
- position: fixed;
- top:0;
- left:0;
- right:0;
- bottom:0;
- padding:10%;
- display: flex;
- align-items: center;
- z-index:1000000;
- transform: translate3d(0,0,0);
-
- &:before {
- content: "";
- position: absolute;
- top:-40rem;
- left:-40rem;
- right:-40rem;
- bottom:-40rem;
- background:var(--color-bg);
- opacity: .5;
- }
- .popup-title {
- position: relative;
- background:var(--color-raised);
- border-bottom: 1rem solid var(--color-bg);
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- height:46rem;
- display: flex;
- padding:0 15rem;
- align-items: center;
-
- &.closable {
- padding-right: 50rem;
- }
- .closer {
- position:absolute;
- right:0rem;
- top:0;
- padding:0 15rem;
- bottom:0;
- display: flex;
- align-items: center;
- color:var(--color-text-fade);
- cursor: pointer;
- }
- }
- .popup-wrapper {
- display: flex;
- flex-direction: column;
- align-items: stretch;
- width:auto;
- max-width:600rem;
- margin:0 auto;
- position: relative;
- overflow: hidden;
- box-shadow: 1rem 0 0 0 var(--color-bg),
- 0 1rem 0 0 var(--color-bg),
- 1rem 1rem 0 0 var(--color-bg),
- 0 1rem 0 0 var(--color-light) inset;
- border-left:1rem solid var(--color-bg);
- border-top:1rem solid var(--color-bg);
- .popup-content {
- height:100%;
- width:100%;
- flex:1;
- padding:10rem;
- overflow-y:auto;
- white-space: normal;
- background:var(--color-fg);
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- text-transform: none;
- position: relative;
- }
- }
-}
diff --git a/src/browser/scss/widgets/_fader.scss b/src/browser/scss/widgets/_fader.scss
deleted file mode 100644
index fb5568ff..00000000
--- a/src/browser/scss/widgets/_fader.scss
+++ /dev/null
@@ -1,366 +0,0 @@
-.fader-container {
- --color-pips: var(--color-custom);
- --color-gauge: var(--color-custom);
- --color-knob: var(--color-custom);
- padding: 1rem;
- width:100rem;
- height:300rem;
- &.horizontal {
- height:130rem;
- width:300rem
- }
-}
-
-.panel:not(.tab) > .fader-container {
- padding: 0rem;
- --color-border:transparent;
- > .fader.compact {
- padding: 1rem;
- }
- > .fader.compact > .wrapper {
- box-shadow: 0 0 0 1rem var(--color-fg);
-
- outline: 1rem solid var(--color-light);
- border: 1rem solid var(--color-bg);
- }
-}
-
-.fader {
- height:100%;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- position: relative;
- flex: 1;
- > .input {
- height: 25rem;
- flex:initial!important;
- flex-shrink: 0!important;
- display: block;
- background: transparent!important;
- border: 0!important;
- }
-
- .wrapper {
- overflow: hidden;
- flex: 1 1 100%;
- max-height: 100%;
- width: 100%;
- position: relative;
- display: flex;
- justify-content: center;
- border-radius: inherit;
- touch-action: none;
-
- > * {
- pointer-events: none;
- }
-
- > canvas {
- width: 20rem;
- image-rendering:pixelated;
- position: relative;
- z-index: 1;
- }
-
- .meter-container {
- height: auto;
- width:6rem!important;
- min-width: auto;
- flex-grow: 0;
- --color-border:transparent;
- border:0;
- margin: 20rem 6rem 20rem 0;
- order: -1
- }
-
- .pips {
- width: 35rem;
- // background-color: var(--color-light);
- position: relative;
- margin: 23rem 0rem 21rem -10rem;
- z-index: 0;
-
- .pip {
- height:1rem;
- // background: var(--color-track);
- color:var(--color-fg);
- position: absolute;
- left:0;
-
- &:before {
- content:"";
- position: absolute;
- top:0;
- left:-12rem;
- width:5rem;
- bottom:0;
- background: var(--color-custom);
- opacity: 0.5;
- box-shadow: 0 0 0 1rem var(--color-bg),
- 0 0 0 2rem var(--color-light);
- }
- &:after {
- content:"";
- position: absolute;
- top:0;
- left:7rem;
- width:5rem;
- bottom:0;
- background: var(--color-custom);
- opacity: 0.5;
- box-shadow: 0 0 0 1rem var(--color-bg),
- 0 0 0 2rem var(--color-light);
- }
-
- span {
- position: absolute;
- width:30rem;
- display: block;
- text-align: center;
- font-size:90%;
- line-height: 12rem;
- left:15rem;
- top:-5.5rem;
- color:var(--color-text-fade);
- text-transform: none;
- }
- }
- }
-
- }
-
- &.align-right {
- .wrapper {
- flex-direction: row-reverse;
- .meter-container {
- margin: 20rem 0rem 20rem 6rem;
- }
- .pips {
- margin: 23rem -10rem 21rem 0rem;
- // margin: 23rem 5rem 21rem 12rem;
- // background-position: top right;
- .pip {
- right:0;
- left:auto;
- // margin-bottom: 0;
- span {
- right:15rem;
- left:auto;
- }
- }
- }
- }
- }
-
- &.horizontal {
- .wrapper {
- flex-direction: column;
- > canvas {
- width: auto;
- height: 20rem;
- }
-
- .meter-container {
- width: auto!important;
- height:6rem;
- min-height: auto;
- margin: 0 20rem 6rem 20rem;
- }
-
- .pips {
- width:auto;
- height: 25rem;
- margin: -10rem 22rem 0 22rem;
- .pip {
- width:1rem;
- height:5rem;
- &:before {
- left:0;
- top:-12rem;
- height:5rem;
- right:0;
- width:1rem;
- }
- &:after {
- left:0;
- top:7rem;
- height:5rem;
- right:0;
- width:1rem;
- }
- span {
- top:20rem;
- left:-14rem!important;
- right:auto;
- }
-
- }
- }
- }
- }
-
- &.compact {
- .wrapper {
- border: 1rem solid var(--color-bg);
- > canvas {
- flex: 1 1 100%;
- background: var(--color-track);
- order:1;
- }
- .meter-container {
- order:3;
- margin: 0;
- border: 0;
- box-shadow: none;
- padding: 0;
- .fader {
- border: 0;
- border-left: 1rem solid var(--color-bg);
- .wrapper {
- border: 0;
- }
- }
- .pips {
- display: none;
- }
- }
- > .pips {
- overflow: hidden;
- margin: 0;
- order:2;
- background: var(--color-track);
- border:0;
- border-left: 1rem solid var(--color-bg);
- width: 3rem;
- .pip {
- left:0;
- right: 0;
- span {
- display: none;
- }
- &:before {
- content:none;
- }
- &:after {
- left:0;
- right: 0;
- box-shadow: none;
- opacity: 1;
- }
- &:not(:last-child):not(:first-child) {
- margin-bottom: -1rem;
- }
- }
- }
- }
-
- &.align-right {
- .wrapper {
- .meter-container {
- .fader {
- border: 0;
- border-right: 1rem solid var(--color-bg);
- }
- }
- .pips {
- border:0;
- border-right: 1rem solid var(--color-bg);
- }
- }
- }
-
-
- --input-margin:0rem;
- &.has-meter {
- --input-margin:-3rem;
- }
- &.has-pips {
- --input-margin:-1rem;
- }
- &.has-meter.has-pips {
- --input-margin:-4rem;
- }
-
- .input {
- pointer-events: none;
- position: absolute;
- border:0;
- background:transparent;
- overflow: hidden;
- position: absolute;
- top:50%;
- left:50%;
- z-index: 1;
- }
-
- &.horizontal {
- position:relative;
-
- .wrapper {
- .meter-container {
- .fader {
- border: 0;
- border-top: 1rem solid var(--color-bg);
- }
- }
- }
-
- .input {
- width: 100rem;
- height: 24rem;
- margin-left: -50rem;
- margin-top: calc(-1 * 12rem + var(--input-margin));
- }
-
- .pips {
- height: 3rem;
- border:0;
- border-top: 1rem solid var(--color-bg);
- width: 100%;
- .pip {
- margin: 0;
- &:last-child {
- left:auto!important;
- right:0;
- }
- &:after {
- top:0;
- width: 1rem;
- }
- }
- }
- }
-
- &:not(.horizontal) {
- .input {
- height: 100rem;
- width: 24rem;
- margin-top: -50rem;
- margin-left: calc(-1 * 12rem + var(--input-margin));
- z-index: 3;
- input {
- transform: rotate(-90deg);
- width: 100rem;
- }
- }
-
- &.align-right {
- .input {
- margin-left: calc(-1 * 12rem - var(--input-margin));
- }
- }
-
- .pips {
- .pip:last-child {
- top:0;
- }
- }
- }
-
-
-
- }
-
-
-}
diff --git a/src/browser/scss/widgets/_inputs.scss b/src/browser/scss/widgets/_inputs.scss
deleted file mode 100644
index f4093822..00000000
--- a/src/browser/scss/widgets/_inputs.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-.input-container {
- width: 100rem;
- height: 60rem;
- padding:1rem;
- .input {
-
- }
-}
-.widget {
- .input {
- display: flex;
- flex: 1 1 100%;
- background:transparent;
- color:var(--color-text-fade);
- overflow: hidden;
- text-align:center;
- padding:1rem;
- border: 1rem solid var(--color-bg);
- background: var(--color-track);
- font-size: 109%;
-
- input {
- display: block;
- flex:1;
- max-width: 100%;
- font: inherit;
- border:0;
- padding:0;
- background: transparent;
- color:var(--color-accent);
- border-radius: inherit;
- -webkit-appearance:none;
- text-align:inherit;
- vertical-align: top;
- letter-spacing: 1rem;
- &:focus {
- color:var(--color-custom);
- }
- }
- canvas {
- flex:1;
- max-width: 100%;
- }
- input + canvas {
- display: none;
- width: 0;
- }
-
-
- }
-
-}
-
-.panel:not(.tab) > .input-container {
- padding: 0rem;
- > .input {
- box-shadow: 0 0 0 1rem var(--color-fg);
- margin:1rem;
- outline: 1rem solid var(--color-light);
- border: 1rem solid var(--color-bg);
- }
-}
diff --git a/src/browser/scss/widgets/_knob.scss b/src/browser/scss/widgets/_knob.scss
deleted file mode 100644
index c35da1d0..00000000
--- a/src/browser/scss/widgets/_knob.scss
+++ /dev/null
@@ -1,91 +0,0 @@
-.knob-container, .encoder-container {
- --color-pips: var(--color-custom);
- --color-gauge: var(--color-custom);
- --color-knob: var(--color-custom);
- padding: 1rem;
-
- width: 100rem;
- height: 120rem;
- align-items: center;
- .input {
- // display: none!important;
- }
-}
-
-.knob {
- height:100%;
- width: 100%;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- position: relative;
- flex: 1;
-
- > .input {
- height: 25rem;
- flex:initial!important;
- flex-shrink: 0!important;
- display: block;
- background: transparent!important;
- border: 0!important;
- }
-
- .wrapper {
- overflow: hidden;
- flex: 1 1 100%;
- max-height: 100%;
- width: 100%;
- position: relative;
- display: flex;
- touch-action: none;
- canvas {
- width: 100%;
- position: relative;
- pointer-events: none;
- image-rendering: pixelated;
- }
- }
-
-}
-
-.encoder-container {
-
- --color-gauge: transparent;
-
-}
-
-.encoder {
-
- height:100%;
- width: 100%;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- position: relative;
-
- .wrapper {
- overflow: hidden;
- flex: 1 1 100%;
- max-height: 100%;
- width: 100%;
- position: relative;
- display: flex;
- }
-
- .input {
- display: none;
- }
-
- .display-knob {
- position: absolute;
- top:0;
- bottom:0;
- left:0;
- right:0;
- pointer-events: none;
- }
-
- .drag-knob {
- opacity: 0;
- }
-}
diff --git a/src/browser/scss/widgets/_maths.scss b/src/browser/scss/widgets/_maths.scss
deleted file mode 100644
index e0b04951..00000000
--- a/src/browser/scss/widgets/_maths.scss
+++ /dev/null
@@ -1,28 +0,0 @@
-.formula-container {
- width: 100rem;
- height:60rem;
- padding:1rem;
- .formula {
- display:flex;
- height:100%;
- background: var(--color-track);
- border:1rem solid var(--color-bg);
- .input {
- background: transparent!important;
- border: 0!important;
- --color-text: var(--color-custom);
- pointer-events: none;
- }
- }
-}
-
-.panel:not(.tab) > .formula-container {
- --color-border:transparent;
- padding: 0rem;
- .formula {
- margin: 1rem;
- box-shadow: 0 0 0 1rem var(--color-fg);
- outline:1rem solid var(--color-light);
- border: 1rem solid var(--color-bg);
- }
-}
diff --git a/src/browser/scss/widgets/_matrices.scss b/src/browser/scss/widgets/_matrices.scss
deleted file mode 100644
index 2a5eca0d..00000000
--- a/src/browser/scss/widgets/_matrices.scss
+++ /dev/null
@@ -1,151 +0,0 @@
-/* Multiple widgets (push|toggle|fader) matrix */
-.multitoggle-container, .multipush-container, .multifader-container {
- &.editing {
- overflow: hidden;
- }
- height:200rem;
- width:200rem;
- &.nolabel .matrix {
- top:0;
- }
-
-}
-
-.matrix {
- flex: 1 1 100%;
- overflow: auto;
- display: flex;
- flex-wrap: wrap;
- flex-direction: row;
- padding:1rem 2rem 2rem 1rem;
- touch-action: none;
-
- > .widget {
- min-height: 0;
- min-width: 0;
- height: auto;
- width: calc( 100% / var(--columns) - var(--spacing));
- margin: calc(var(--spacing) / 2);
- .label {
- background:none;
- border:0;
- }
- }
-}
-
-.multifader-container {
- .matrix {
- align-items:stretch;
- flex-wrap: nowrap;
- &.horizontal {
- flex-direction: column;
- display: flex;
- .fader-container {
- flex-direction: row;
- flex:1;
- .fader {
- width:100%;
- }
- .label {
- width:30rem;
- height:auto;
- max-height: initial;
- margin-right: -5rem;
- }
- }
-
- }
- > .widget {
- height: auto;
- flex:1;
-
- > .fader {
- height: auto;
- flex: 1 1 100%;
-
- }
- }
- &.compact {
- > .widget {
- box-shadow: 1rem 0 0 0 var(--color-bg),
- 0 1rem 0 0 var(--color-bg),
- 1rem 1rem 0 0 var(--color-bg);
- .label {
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- }
- padding:0;
- .wrapper {
- border:0;
- border-top:1rem solid var(--color-bg);
- canvas{
- border:none;
- }
- }
- }
- &.horizontal {
- > .widget {
- .wrapper {
- border:0;
- border-left:1rem solid var(--color-bg);
- }
- .label {
- margin-right: 0;
- }
- }
- }
- }
- }
- .fader-wrapper {
- padding:10rem 0 20rem!important;
- .fader {
- left:0!important;
- }
- }
-
-}
-
-.keyboard-container {
- --color-black-key: var(--color-raised);
- --color-white-key: #aaa;
- height:90rem;
- width:240rem;
- .matrix {
- position: relative;
- overflow: hidden;
- > .widget {
- border-radius: 0!important;
- &.white:first-child {
- border-top-left-radius:inherit!important;
- border-bottom-left-radius:inherit!important;
- }
- &.white:last-child {
- border-top-right-radius:inherit!important;
- border-bottom-right-radius:inherit!important;
- }
- }
- .white {
- --color-raised: var(--color-white-key);
- .toggle:before {
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 0 0 1rem var(--color-light) inset;
- }
-
-
- }
- .black {
- --color-raised: var(--color-black-key);
- position: absolute;
- z-index: 2;
- top:1rem;
- height: 65%;
- .toggle:before {
- border-bottom:2rem solid var(--color-bg);
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 -1rem 0 0 var(--color-light) inset;
- }
- }
- .on {
- background: var(--color-custom)
- }
- }
-}
diff --git a/src/browser/scss/widgets/_pads.scss b/src/browser/scss/widgets/_pads.scss
deleted file mode 100644
index f0509f3d..00000000
--- a/src/browser/scss/widgets/_pads.scss
+++ /dev/null
@@ -1,188 +0,0 @@
-.xy-container, .rgb-container, .multixy-container {
- width:200rem;
- height:230rem;
- padding:1rem;
-
- .label {
- flex-shrink: 0;
- z-index: 1;
- }
-
- .pad {
- height:100%;
- width: 100%;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- > .input {
- margin-top: 2rem;
- height: 25rem;
- flex:initial!important;
- flex-shrink: 0!important;
- background: transparent!important;
- border: 0!important;
- }
- > .wrapper {
- position: relative;
- flex:1;
- background:var(--color-track);
- border: 1rem solid var(--color-bg);
- touch-action: none;
-
- > canvas {
- width:100%;
- height:100%;
- position: absolute;
- pointer-events: none;
- z-index: 1;
- }
- .fader {
- pointer-events: none;
- position: absolute;
- width:100%;
- height:100%;
- z-index: 0;
- --color-knob:transparent;
- --color-gauge:transparent;
- box-shadow: none;
- border: 0;
- * {
- background: transparent!important;
-
- }
- .wrapper {
- border:none;
- }
- .input {
- display: none;
- }
- }
- }
- }
-
-
-}
-
-.panel:not(.tab) > .xy-container,
-.panel:not(.tab) > .rgb-container,
-.panel:not(.tab) > .multixy-container {
- --color-border:transparent;
- padding: 0;
- > .pad {
- padding: 1rem;
- }
- > .pad > .wrapper {
- outline:1rem solid var(--color-light);
- box-shadow: 0 0 0 1rem var(--color-fg);
- border: 1rem solid var(--color-bg);
- }
- .hue-wrapper {
- outline:1rem solid var(--color-light);
- box-shadow: 0 0 0 1rem var(--color-fg);
- }
-}
-
-.rgb-container {
- > .pad {
- > .wrapper {
- // background: none!important;
-
- image-rendering:pixelated;
- > .pad {
- --color-custom:var(--color-white);
- position: absolute;
- .wrapper {
- border:0;
- background: transparent;
- }
- canvas {
- border:0;
- left:0;
- }
- .input {
- display: none;
- }
- }
- > canvas {
- top:var(--pointSize);
- left:var(--pointSize);
- flex:0;
- height:calc(100% - 2 * var(--pointSize));
- width:calc(100% - 2 * var(--pointSize));
- background-color: red;
- background-clip: content-box;
- background-image: linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,1) 100%), linear-gradient(to right, rgba(255,255,255,1) 0%, rgba(255,255,255,0) 100%);
- opacity: 0.7;
- }
- }
- .hue-wrapper {
- --color-gauge:transparent;
- --color-knob:var(--color-white);
- margin-top: -1rem;
- height: calc(2 * var(--pointSize) + 8rem);
- .wrapper {
- &:after {
- content:"";
- display: block;
- position: absolute;
- top:50%;
- margin-top: -2rem;
- left:var(--pointSize);
- right:var(--pointSize);
- height: 4rem;
- background: linear-gradient(to left, #F00, #FF0080, #F0F, #8000FF, #00F, #0080FF, #0FF, #00FF80, #0F0, #80FF00, #FF0, #FF8000, #F00) repeat scroll 0% 0%;
- box-shadow: 0 0 0 4rem var(--color-track);
- z-index: 1;
- }
- background:var(--color-track);
- }
- canvas {
- background:transparent;
- opacity: 0.7;
- margin: 2rem 0;
- }
- }
- }
-}
-
-
-.multixy-container {
- > .pad {
- text-align: center;
- font-size: 109%;
-
- > .wrapper {
-
- > canvas {
- top:0;
- left:0;
- }
- .handle {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom:0;
- z-index: 1;
- &.active {
- pointer-events: none;
- }
- }
- > .pad {
- pointer-events: none;
- position: absolute;
- .wrapper {
- border:0;
- background: transparent;
- }
- canvas {
- border:0;
- left:0;
- }
- .input {
- display: none;
- }
- }
- }
- }
-}
diff --git a/src/browser/scss/widgets/_panel.scss b/src/browser/scss/widgets/_panel.scss
deleted file mode 100644
index bffd4914..00000000
--- a/src/browser/scss/widgets/_panel.scss
+++ /dev/null
@@ -1,301 +0,0 @@
-.panel-container-base {
- --color-border:var(--color-bg);
- z-index: 1;
-
- box-shadow: 1rem 0 0 0 var(--color-border),
- 0 1rem 0 0 var(--color-border),
- 1rem 1rem 0 0 var(--color-border);
-
- > .label {
- border-bottom:1rem solid var(--color-border);
- z-index: 20;
- box-shadow: 0 0 0 1rem var(--color-light) inset;
- background: var(--color-fg);
- }
-
- .panel {
- overflow: auto;
- position: absolute;
- top:29rem;
- left:-1rem;
- right:0;
- bottom:0;
- background: var(--color-fg);
- --color-border: var(--color-fg);
-
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 0 0 1rem var(--color-fg) inset,
- 1rem 1rem 0 1rem var(--color-light) inset;
-
- &.tab, &.root, &.has-tabs {
- background: var(--color-bg);
- --color-border: var(--color-bg);
- box-shadow: none;
-
- }
- &:not(.tab) {
- > .widget {
- box-shadow: 1rem 0 0 0 var(--color-border),
- 0 1rem 0 0 var(--color-border),
- 1rem 1rem 0 0 var(--color-border);
- --default-bg: transparent;
- }
- }
- &.has-tabs {
- top:30rem;
- display: flex;
- flex-direction: column;
- background: var(--color-bg);
-
- > .tabs-wrapper {
- background: var(--color-fg);
- display: flex;
- flex-direction: column;
- left:-1rem;
- > .widget {
- background: none;
- border-top:none;
- // border-right:1rem solid transparent;
- }
- }
- }
-
- &.noscroll {
- overflow: hidden;
- > .widget {
- max-width: 100%;
- max-height: 100%;
- }
- }
-
- > .tabs-wrapper {
- flex: 1 1 100%;
- min-height:0;
- > .tab-container {
- // width: 100%;
- > .label {
- display: none;
- }
-
- }
- }
-
- }
- &.nolabel {
- > .panel {
- top:-1rem;
- }
- > .panel.has-tabs {
- top:0;
- }
-
- }
-
- &.noborder {
-
- --color-border: var(--color-fg);
- > .panel {
- box-shadow: none;
- }
-
- }
-
-}
-
-
-.panel-container {
- @extend .panel-container-base;
-
- width: 200rem;
- height: 200rem;
-
- background: var(--color-fg);
-
-}
-
-.strip-container {
- @extend .panel-container-base;
-
- width: 100rem;
- height: 300rem;
-
- background: var(--color-fg)!important;
-
- &.horizontal {
- width: 300rem;
- height: 100rem;
- }
-
- &.vertical {
- > .panel {
-
- display: flex;
- flex-direction: column;
- align-items: stretch;
- padding: calc(var(--spacing) / 2 * 1rem);
- > .widget {
- width: auto!important;
- max-width: 100%;
- margin: calc(var(--spacing) / 2 * 1rem);
- }
- }
- }
- &.horizontal {
- > .panel {
- display: flex;
- flex-direction: row;
- align-items: stretch;
- padding: calc(var(--spacing) / 2 * 1rem);
- > .widget {
- height: auto!important;
- max-height: 100%;
- margin: calc(var(--spacing) / 2 * 1rem);
- }
- }
-
- }
- &.stretch > .panel > .widget {
- flex:1 1 100%;
- }
-
-}
-.editor-enabled .strip-container {
- &.horizontal > .panel > .widget > .ui-resizable-s,
- &.vertical > .panel > .widget > .ui-resizable-e,
- > .panel > .widget > .ui-resizable-se {
- display: none!important;
- }
-}
-
-.modal-container {
- @extend .toggle-container;
-
- > .toggle:after {
- content:"\f0da"!important;
- font-family: FontAwesome;
- transform: rotateZ(-45deg);
- font-size: 20rem;
- display: block;
- width:8rem;
- height:6rem;
- right:2rem!important;
- top:1rem!important;
- left:auto!important;
- bottom:auto!important;
- line-height: 10rem;
- text-align: center;
- float:right;
- position: absolute;
- box-shadow: none;
- background: none!important;
- color:var(--color-text-fade);
- opacity: 1!important;
- }
-
- > .panel {
- display: none;
- }
- > .popup {
- padding:0;
- > .popup-wrapper {
- max-width: 100%;
- max-height: 100%;
- width: var(--width, 100%);
- height: var(--height, 100%);
- .popup-content {
- padding:0;
- background: transparent;
- > .panel {
- background-color: var(--color-fg);
- position: absolute;
- width: auto;
- height: auto;
- top:-1rem;
- left:-1rem;
- right:0rem;
- bottom:0rem;
- }
- }
- .popup-title {
- z-index: 1;
- }
- }
- }
- &.editing .popup-wrapper:after {
- content:"";
- z-index: 999;
- position: absolute;
- top:0;
- left:0;
- right:0;
- bottom:0;
- border:1rem dashed var(--color-accent);
- pointer-events: none;
- }
- &.on {
- z-index: initial;
- > .toggle:after {
- color:var(--color-custom);
- }
- border-radius: 0!important; // border radius breaks it somehow
- }
-
-}
-
-.root-container {
- @extend .panel-container-base;
- height: 100%;
- border:none;
- > .label {
- display: none;
- }
-
-}
-
-
-.tab-container, .root-container {
- height: 100%;
- flex:1;
- box-shadow: none;
- background: var(--color-bg)!important;
-
- > .panel {
- transform: rotateZ(0);
- top:0rem;
- left:-1rem;
- right:0rem;
- &.has-tabs {
- top:1rem;
- }
- }
-}
-
-.clone-container {
- width: 100rem;
- height: 100rem;
- > .label {
- display: none;
- }
- .clone {
- position: relative;
- height: 100%;
- width: 100%;
- > .widget {
- border:0!important;
- box-shadow: none!important;
- background: transparent!important;
- position: relative!important;
- left:auto!important;
- bottom:auto!important;
- right:auto!important;
- top: auto!important;
- width: 100%!important;
- height: 100%!important;
- min-height: initial!important;
- max-height: initial!important;
- min-width: initial!important;
- max-width: initial!important;
- padding: 0!important;
- }
- }
-}
diff --git a/src/browser/scss/widgets/_plots.scss b/src/browser/scss/widgets/_plots.scss
deleted file mode 100644
index 8dd7d109..00000000
--- a/src/browser/scss/widgets/_plots.scss
+++ /dev/null
@@ -1,96 +0,0 @@
-.led-container, .rgbled-container {
- width:100rem;
- height:100rem;
- padding:1rem;
- .led {
- display: flex;
- flex-direction: row;
- flex: 1 1 100%;
- background: var(--color-track);
- border:1rem solid var(--color-bg);
- --opacity: 0;
- &:after {
- content:"";
- width:100%;
- height: 100%;
- background: var(--color-custom);
- border-radius: inherit;
- opacity: var(--opacity);
- }
- }
-}
-
-.rgbled-container .led {
- --opacity: 1;
-}
-
-.plot-container, .visualizer-container, .eq-container {
- height: 200rem;
- width: 200rem;
- padding:1rem;
- .plot {
- display: flex;
- flex-direction: row;
- flex: 1 1 100%;
- position: relative;
- background: var(--color-track);
- border:1rem solid var(--color-bg);
- }
- canvas {
- flex:1;
- image-rendering:pixelated;
- width: 100%;
- }
-}
-
-
-.meter-container {
- @extend .fader-container;
- --color-knob: transparent;
- .wrapper {
- pointer-events: none;
- }
-}
-
-.text-container {
- width: 100rem;
- height:60rem;
- flex-shrink: 0;
- padding:1rem;
- .text {
- flex: 1 1 100%;
- height:35rem;
- padding: 10rem;
- justify-content: center;
- display: flex;
- align-items: center;
- background: var(--color-track);
- color:var(--color-custom);
- border: 1rem solid var(--color-bg);
- &.vertical {
- transform: rotate(180deg);
- text-overflow: ellipsis;
- overflow: hidden;
- -webkit-writing-mode:vertical-lr;
- writing-mode:vertical-lr;
- }
- }
-}
-
-.panel:not(.tab) > .led-container,
-.panel:not(.tab) > .rgbled-container,
-.panel:not(.tab) > .text-container,
-.panel:not(.tab) > .visualizer-container,
-.panel:not(.tab) > .eq-container,
-.panel:not(.tab) > .plot-container {
- --color-border:transparent;
- padding: 0rem;
- .plot, .text, .led {
- padding: 0rem;
- margin: 1rem;
- background-clip: content-box;
- box-shadow: 0 0 0 1rem var(--color-fg);
- outline:1rem solid var(--color-light);
- border: 1rem solid var(--color-bg);
- }
-}
diff --git a/src/browser/scss/widgets/_push.scss b/src/browser/scss/widgets/_push.scss
deleted file mode 100644
index 9dc1cb3c..00000000
--- a/src/browser/scss/widgets/_push.scss
+++ /dev/null
@@ -1,24 +0,0 @@
-.push-container {
- @extend .toggle-container;
- .toggle {
- &.active {
- // background-color: var(--color-fg);
- &:after {
- content: "";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.4;
- background: radial-gradient( ellipse at center, transparent, var(--color-bg));
- }
- }
- &.on:not(.active) {
- &:after {
- opacity: 0;
- }
- }
- }
-
-}
diff --git a/src/browser/scss/widgets/_switch.scss b/src/browser/scss/widgets/_switch.scss
deleted file mode 100644
index 70c8a43c..00000000
--- a/src/browser/scss/widgets/_switch.scss
+++ /dev/null
@@ -1,219 +0,0 @@
-.switch-container, .switcher-container, .crossfader-container {
- z-index: 1;
- width:100rem;
- height:100rem;
- padding:1rem;
-
- &.nolabel {
- --color-border:var(--color-bg);
- padding: 0;
- .switch, .switcher {
- border: 0;
- }
- }
- .switch {
- cursor: pointer;
- display: flex;
- flex-direction:column;
- align-items: stretch;
- flex: 1;
- z-index: 1;
- background:var(--color-bg);
- border: 1rem solid var(--color-bg);
-
- &.horizontal {
- flex-direction:row;
- .value {
- text-align: center;
- display: flex;
- justify-content: center;
- flex-direction: column;
- border-top:0;
- border-right:1rem solid var(--color-bg);
- flex: 1 1 100%;
- height:auto;
- margin-bottom:0;
- &:last-child {
- border-right:0;
- }
-
- }
- }
- .value {
- background:var(--color-raised);
- padding:6rem;
- color:var(--color-text);
- width:100%;
- flex: 1 1 100%;
- position: relative;
- // border-top: 1rem solid var(--color-bg);
- margin-bottom:1rem;
- white-space: normal;
- text-align: center;
- word-break: break-all;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- justify-content: center;
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 1rem 0 0 var(--color-light) inset;
-
- &:before {
- content:"";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0;
- box-shadow: 0 0 0 1rem var(--color-custom) inset;
- border-radius: inherit;
- }
-
- &.on {
- // background: var(--color-fg);
- color: var(--color-custom);
- &:after {
- content: "";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.4;
- background: radial-gradient( ellipse at center, transparent, var(--color-bg));
- }
- &:before {
- opacity: 0.3
- }
- }
- &:first-child {
- // border-top:0;
- }
-
- &:last-child {
- margin-bottom:0;
- }
-
- i {
- width: auto;
- }
-
- }
- }
-}
-
-.switcher-container {
- .switcher {
- flex:1;
- display:flex;
- }
-}
-
-.crossfader-container {
- .switcher {
- flex: 1 1 100%;
- width:auto;
- display:flex;
- border: 1rem solid var(--color-bg);
- padding: 2rem;
- .switch {
- flex:2;
- height: auto;
- border: 1rem solid var(--color-bg) !important;
- }
- &.horizontal {
- flex-direction: column;
- .switch {
- flex:2;
- height: auto;
- }
- .fader-container {
- width: 100%;
- height: auto;
- }
- }
- }
- .fader-container {
- height: 100%;
- flex:3;
- .input {
- display: none;
- }
- }
-}
-.panel:not(.tab) > .crossfader-container {
- --color-border:var(--color-fg);
- .switcher {
- border:0!important;
- }
-}
-
-.dropdown-container {
-
- z-index: 1;
- width:100rem;
- height: 60rem;
- padding:1rem;
- &.noselect .select:before {
- content:"...";
- position: absolute;
- padding-left:10rem;
- left:0;
- top:50%;
- margin-top:-12rem;
- height: 20rem;
- line-height: 20rem;
- pointer-events: none;
- }
- &.nolabel {
- --color-border:var(--color-bg);
- padding: 0;
- .select {
- border: 0;
- }
- }
- .select {
- flex: 1 1 100%;
- position: relative;
- overflow: hidden;
- cursor: pointer;
- border: 1rem solid var(--color-bg);
- display: flex;
- border-radius: inherit;
-
- select {
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 1rem 0 0 var(--color-light) inset;
- flex:1;
- display: flex;
- vertical-align: middle;
- background:transparent;
- padding: 0 20rem 0 10rem;
- -webkit-appearance:none;
- -moz-appearance:none;
- appearance:none;
- background: var(--color-raised);
- color:inherit;
- font-size: 109%!important;
- line-height: 120%!important;
- text-transform: none;
- border-radius: inherit;
- }
- &:after{
- content:"\f107";
- font-family: FontAwesome;
- position: absolute;
- padding:0 10rem;
- right:0;
- top:50%;
- margin-top:-11rem;
- font-size: 180%;
- height: 20rem;
- line-height: 20rem;
- pointer-events: none;
- }
-
- }
-
-}
diff --git a/src/browser/scss/widgets/_toggle.scss b/src/browser/scss/widgets/_toggle.scss
deleted file mode 100644
index 8a620651..00000000
--- a/src/browser/scss/widgets/_toggle.scss
+++ /dev/null
@@ -1,101 +0,0 @@
-.toggle-container {
- width:100rem;
- height: 60rem;
- padding:0!important;
- --color-border:var(--color-bg);
- --default-bg: var(--color-raised)!important;
- z-index: 1;
-
- .toggle {
-
- cursor: pointer;
- flex: 1 1 100%;
- display: flex;
- border-radius: inherit!important;
- touch-action: none;
-
- &:before {
- content:"";
- flex: 1 1 100%;
- opacity: 1;
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 1rem 0 0 var(--color-light) inset;
- border-radius: inherit;
- }
-
- &.on {
- &:after {
- content: "";
- position: absolute;
- top:0;
- left: 0;
- right: 0;
- bottom: 0;
- opacity: 0.4;
- background: radial-gradient( ellipse at center, transparent, var(--color-bg));
- }
-
- &:before {
- opacity: 0.3;
- box-shadow: 0 0 0 1rem var(--color-custom) inset;
- }
-
- }
-
- }
-
- > .label {
- position: absolute;
- top:2rem;
- left:2rem;
- right:2rem;
- bottom:2rem;
- height:auto;
- width: auto;
- max-height: initial;
- border:0!important;
- background: none!important;
- text-align: center;
- pointer-events:none;
- display: flex;
- justify-content: center;
- align-items: center;
- z-index: 2;
- }
-
- &.on > .label {
- color: var(--color-custom);
- opacity: 1;
- }
-
- &.led {
- .toggle:after {
- content:"";
- opacity: 1;
- position: absolute;
- display: block;
- top:3rem;
- left:3rem;
- right:3rem;
- height: 4rem;
- background: var(--color-track);
- box-shadow: 0 0 0 1rem var(--color-light), 0 0 0 1rem var(--color-bg) inset;
- z-index: 1;
- border-radius: inherit;
- opacity: 0.9;
- }
- .toggle.on:after {
- opacity: 0.7;
- background: var(--color-custom);
- }
- .toggle:before {
- opacity: 1;
- box-shadow: 0 0 0 1rem var(--color-light) inset,
- 0 1rem 0 0 var(--color-light) inset;
- }
- > .label {
- top:7rem;
- }
- }
-
-}
diff --git a/src/client/backup.js b/src/client/backup.js
new file mode 100644
index 00000000..98a264c4
--- /dev/null
+++ b/src/client/backup.js
@@ -0,0 +1,59 @@
+var cache = require('./managers/cache'),
+ localBackup = cache.get('backup', false)
+
+
+module.exports = {
+
+ exists: localBackup !== null,
+
+ save: ()=>{
+
+ var session = require('./managers/session/'),
+ state = require('./managers/state'),
+ editor = require('./editor/')
+
+ if (session.session) {
+ cache.set('backup', {
+ session: session.session.data,
+ sessionPath: session.sessionPath,
+ state: state.get(),
+ history: editor.history,
+ historyState: editor.historyState,
+ editorEnabled: editor.enabled
+ }, false)
+ }
+
+ },
+
+ load: ()=>{
+
+ var session = require('./managers/session/'),
+ state = require('./managers/state'),
+ editor = require('./editor/'),
+ ipc = require('./ipc/')
+
+ if (localBackup) {
+
+ var data = localBackup
+
+ cache.remove('backup', false)
+ session.load(data.session, ()=>{
+
+ state.set(data.state, false)
+
+ editor.clearHistory()
+ editor.history = data.history
+ editor.historyState = data.historyState
+
+ if (data.editorEnabled) editor.enable()
+
+
+ ipc.send('sessionSetPath', {path: data.sessionPath})
+ session.setSessionPath(data.sessionPath)
+
+ })
+
+ }
+
+ }
+}
diff --git a/src/client/dom.js b/src/client/dom.js
new file mode 100644
index 00000000..cb455cfe
--- /dev/null
+++ b/src/client/dom.js
@@ -0,0 +1,107 @@
+var readyCallbacks = [],
+ initState = false
+
+module.exports = {
+
+ init: function() {
+
+ for (var i in readyCallbacks) {
+ readyCallbacks[i]()
+ }
+
+ initState = true
+
+ },
+
+ ready: function(callback) {
+ if (initState) {
+ callback()
+ } else {
+ readyCallbacks.push(callback)
+ }
+ },
+
+ dispatchEvent: function(element, name, data) {
+
+ var event = new CustomEvent(name, {
+ detail: data,
+ bubbles: true,
+ cancelable: true
+ })
+
+ element.dispatchEvent(event)
+
+ },
+
+ addEventListener: function(element, events, listener, capture) {
+
+ var eventsAsObject = typeof events == 'string' ? events.split(' ') : events
+
+ for (var i in eventsAsObject) {
+
+ element.addEventListener(eventsAsObject[i], listener, capture)
+
+ }
+
+ },
+
+ get: function(a, b) {
+
+ var context = b ? a : document,
+ selector = b || a,
+ nodes
+
+ if (selector.indexOf('>') === 0) selector = ':scope ' + selector
+
+ if (selector.indexOf(' ') === -1 && selector.indexOf(',') === -1) {
+ if (selector.indexOf('#') === 0 && context === document) {
+ nodes = [document.getElementById(selector.substr(1, selector.length - 1))]
+ } else if (selector.indexOf('.') === 0) {
+ nodes = context.getElementsByClassName(selector.substr(1, selector.length - 1))
+ }
+ }
+
+ if (!nodes) nodes = context.querySelectorAll(selector)
+
+ return [...nodes]
+
+ },
+
+ each: function(context, selector, callback) {
+
+ var nodes = module.exports.get(context, selector)
+
+ nodes.forEach(callback)
+
+ return nodes
+
+ },
+
+ index: function(element) {
+ var parent = element.parentNode
+ return parent ? Array.prototype.indexOf.call(parent.children, element) : -1
+ },
+
+ offset: function(element, container) {
+
+ var offsetLeft = 0,
+ offsetTop = 0
+
+ if (element) {
+ do {
+ if (!isNaN(element.offsetLeft)) {
+ offsetLeft += element.offsetLeft - element.scrollLeft
+ }
+ if (!isNaN(element.offsetTop)) {
+ offsetTop += element.offsetTop - element.scrollTop
+ }
+ } while ((element = element.offsetParent) && element !== container)
+ }
+
+ return {
+ left: offsetLeft,
+ top: offsetTop
+ }
+ }
+
+}
diff --git a/src/client/editor/context-menu.js b/src/client/editor/context-menu.js
new file mode 100644
index 00000000..b572cf84
--- /dev/null
+++ b/src/client/editor/context-menu.js
@@ -0,0 +1,230 @@
+var {updateWidget} = require('./data-workers'),
+ {categories} = require('../widgets/'),
+ widgetManager = require('../managers/widgets'),
+ {icon} = require('../ui/utils'),
+ editor = require('./'),
+ locales = require('../locales'),
+ ContextMenu = require('../ui/context-menu'),
+ contextMenu = new ContextMenu()
+
+
+var multiSelectKey = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
+
+var handleClick = function(event) {
+
+ if (!editor.enabled) return
+
+ if (!event.detail[multiSelectKey] && event.type !== 'fast-right-click' && (
+ event.target.classList.contains('no-widget-select') ||
+ event.target.id === 'open-toggle'
+ )) { return }
+
+ var eventData = event.detail,
+ targetWidget = widgetManager.getWidgetByElement(eventData.target, ':not(.not-editable)')
+
+ if (!targetWidget) return
+
+ // if the widget is not already selected
+ if (!targetWidget.container.classList.contains('editing') || event.detail.ctrlKey || event.detail.shiftKey) {
+ // add a flag to the original event to prevent draginit
+ // and prevent any further fast-click (ie input focus)
+ eventData.capturedByEditor = true
+ event.capturedByEditor = true
+ }
+
+
+ if (event.type !== 'fast-right-click') {
+ editor.select(targetWidget, {multi: event.detail[multiSelectKey]})
+ }
+
+ // right-click menu
+ if (event.type !== 'fast-right-click') return
+
+ if (!event.detail.shiftKey && !event.detail[multiSelectKey] && editor.selectedWidgets.length <= 1) {
+ editor.select(targetWidget)
+ }
+
+ if (!editor.selectedWidgets.length) return
+
+ var data = editor.selectedWidgets.map((w)=>w.props),
+ widget = editor.selectedWidgets[0],
+ parent = widget.parent,
+ actions = []
+
+ var clickX = Math.round((eventData.offsetX + eventData.target.scrollLeft) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH,
+ clickY = Math.round((eventData.offsetY + eventData.target.scrollTop) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH
+
+ if (parent !== widgetManager) {
+
+ if (event.target.tagName !== 'LI') {
+ actions.push({
+ label: icon('project-diagram') + ' ' + locales('editor_show_in_tree'),
+ action: ()=>{
+ editor.widgetTree.showWidget(editor.selectedWidgets[0])
+ }
+ })
+ actions.push({
+ separator: true
+ })
+
+ }
+
+ actions.push({
+ label: icon('copy') + ' ' + locales('editor_copy'),
+ action: editor.copyWidget.bind(editor)
+ })
+
+ actions.push({
+ label: icon('cut') + ' ' + locales('editor_cut'),
+ action: editor.cutWidget.bind(editor)
+ })
+
+ }
+
+ if (widget.childrenType !== undefined) {
+
+ if (editor.clipboard !== null) {
+
+ var pasteActions = [],
+ canPaste = true
+
+ if (
+ editor.clipboard[0].type === 'tab' && widget.childrenType === 'widget' ||
+ editor.clipboard[0].type !== 'tab' && widget.childrenType === 'tab'
+ ) canPaste = false
+
+ if (canPaste) {
+
+ pasteActions.push({
+ label: icon('paste') + ' ' + locales('editor_paste'),
+ action: ()=>{
+ editor.pasteWidget(clickX, clickY)
+ }
+ })
+ pasteActions.push({
+ label: icon('plus-square') + ' ' + locales('editor_pasteindent'),
+ action: ()=>{
+ editor.pasteWidget(clickX, clickY, true)
+ }
+ })
+
+ if (editor.idClipboard && widgetManager.getWidgetById(editor.idClipboard).length && editor.clipboard[0].type !== 'tab') {
+ pasteActions.push({
+ label: icon('clone') + ' ' + locales('editor_clone'),
+ action: ()=>{
+ editor.pasteWidgetAsClone(clickX, clickY)
+ }
+ })
+ }
+
+ }
+
+ actions.push({
+ label: icon('paste') + ' ' + locales('editor_paste'),
+ action: pasteActions,
+ class: canPaste ? '' : 'disabled'
+ })
+
+ }
+
+
+ var addActions = []
+
+ for (let category in categories) {
+
+ var catActions = []
+
+ for (let t in categories[category]) {
+
+ let type = categories[category][t]
+
+ catActions.push({
+
+ label: type,
+ action: ()=>{
+
+ var newData = {type: type}
+
+ if (!eventData.target.classList.contains('tablink')) {
+ newData.top = clickY
+ newData.left= clickX
+ }
+
+ if (editor.usePercents) {
+ newData.top = (100 * clickY / editor.selectedWidgets[0].widget.offsetHeight).toFixed(2) + '%'
+ newData.left= (100 * clickX / editor.selectedWidgets[0].widget.offsetWidth).toFixed(2) + '%'
+ newData.height= '6%'
+ newData.width = '8%'
+ }
+
+ data[0].widgets = data[0].widgets || []
+ data[0].widgets.push(newData)
+
+ var indexes = {addedIndexes: [data[0].widgets.length -1]}
+ updateWidget(editor.selectedWidgets[0], indexes)
+
+
+ editor.pushHistory(indexes)
+
+ }
+ })
+
+ }
+
+ addActions.push({
+ label: category,
+ action: catActions
+ })
+
+ }
+
+ if (actions.length) actions.push({
+ separator: true
+ })
+
+ if (data.length == 1 && widget.childrenType !== 'tab') {
+ actions.push({
+ label: icon('plus') + ' ' + locales('editor_addwidget'),
+ action: addActions
+ })
+ }
+
+ if (data.length == 1 && widget.childrenType !== 'widget') {
+
+ actions.push({
+ label: icon('plus') + ' ' + locales('editor_addtab'),
+ action: ()=>{
+ data[0].tabs = data[0].tabs || []
+ data[0].tabs.push({})
+
+ var indexes = {addedIndexes: [data[0].tabs.length -1]}
+ updateWidget(editor.selectedWidgets[0], indexes)
+ editor.pushHistory(indexes)
+
+ }
+ })
+
+ }
+
+ }
+
+
+ if (parent !== widgetManager) {
+
+ actions.push({
+ separator: true
+ })
+
+ actions.push({
+ label: icon('trash') + ' ' + locales('editor_delete'),
+ action: editor.deleteWidget.bind(editor)
+ })
+
+ }
+
+ contextMenu.open(eventData, actions)
+
+}
+
+document.body.addEventListener('fast-right-click', handleClick, true)
+document.body.addEventListener('fast-click', handleClick, true)
diff --git a/src/client/editor/data-workers.js b/src/client/editor/data-workers.js
new file mode 100644
index 00000000..f8c0cc43
--- /dev/null
+++ b/src/client/editor/data-workers.js
@@ -0,0 +1,237 @@
+var widgetManager = require('../managers/widgets'),
+ resize = require('../events/resize'),
+ stateManager = require('../managers/state'),
+ parser = require('../parser'),
+ Panel,
+ editor,
+ scrollState = {}
+
+setTimeout(()=>{
+ editor = require('./')
+ Panel = require('../widgets/containers/panel')
+})
+
+function updateWidget(widget, options={}) {
+
+ if (options.changedProps) {
+ // alternate routine for small edits
+ var propNames = options.changedProps
+
+ if (
+ // if non dynamic props have changed, skip this and use rebuild routine
+ !propNames.some(n => !widget.isDynamicProp(n))
+ ) {
+
+ var edited = widget.updateProps(options.changedProps, null, {fromEditor: true}) || widget
+
+ editor.widgetTree.updateTree(editor.selectedWidgets)
+
+ if (editor.selectedWidgets.includes(widget) && !options.preventSelect) {
+ editor.select(edited)
+ }
+
+ return edited
+
+ }
+
+ }
+
+
+ if (!widget.mounted) {
+ console.debug(`updateWidget prevented on ${widget.getProp('id')} (widget not mounted yet)`)
+ return
+ }
+
+ var reuseChildren = options.reuseChildren !== false && widget instanceof Panel
+
+ var children = undefined,
+ removedChildren = []
+
+ if (reuseChildren) {
+ children = [...widget.children]
+ if (options.removedIndexes) {
+ options.removedIndexes = options.removedIndexes.sort((a, b) => b - a)
+ for (let i of options.removedIndexes) {
+ removedChildren.push(children.splice(i, 1)[0])
+ }
+ }
+ if (options.addedIndexes) {
+ options.addedIndexes = options.addedIndexes.sort((a, b) => a - b)
+ for (let i of options.addedIndexes) {
+ children.splice(i, 0, null)
+ }
+ }
+
+ }
+
+ // get widget's index
+ var index = widget.parent.children.indexOf(widget)
+
+ // list widgets to remove
+ removedChildren = removedChildren.filter(x => x !== undefined)
+ var removedWidgets = reuseChildren ?
+ removedChildren.map(x => x.getAllChildren().concat(x)).concat(widget).reduce((a,b)=>a.concat(b), []) :
+ widget.getAllChildren().concat(widget)
+
+ // save state
+ if (stateManager.queueCounter === 0) {
+ scrollState = {}
+ }
+ stateManager.incrementQueue()
+ for (let w of removedWidgets) {
+ if (widgetManager.widgets[w.hash]) {
+ let id = w.getProp('id'),
+ value = w.getValue(),
+ valueProp = w.getProp('value')
+
+ stateManager.pushValueState(id, value)
+ if (valueProp !== '' && valueProp !== undefined) stateManager.pushValueOldProp(id, valueProp)
+ }
+ if (widgetManager.scrollingWidgets.indexOf(w.hash) > -1 && w.scroll) {
+ var s = w.scroll()
+ if (s[0] !== 0 || s[1] !== 0) {
+ scrollState[w.getProp('id')] = s
+ }
+ }
+ }
+
+ // remove old widgets
+ widgetManager.removeWidgets(removedWidgets)
+
+ // create new widget
+ var newWidget = parser.parse({
+ data: widget.props,
+ parent: widget.parent,
+ parentNode: widget.parentNode,
+ reCreateOptions: options.reCreateOptions,
+ locals: widget.parsersLocalScope,
+ hash: widget.hash,
+ children: children,
+ index: index
+ })
+
+
+ newWidget.container.parentNode.replaceChild(newWidget.container, widget.container)
+
+ if (newWidget.getProp('type') === 'tab') newWidget.parent.trigger('tab-created', {widget: widget})
+
+
+ if (reuseChildren && !(newWidget instanceof Panel)) {
+ // remove remaining children if widget is not a container anymore
+ widgetManager.removeWidgets(widget.getAllChildren())
+ }
+
+ if (reuseChildren) {
+ // children don't listen to their parent's 'widget-created' event
+ // so we have to let them know it's been updated
+ widgetManager.trigger('prop-changed', {
+ id: newWidget.getProp('id'),
+ props: [],
+ widget: newWidget,
+ options: {}
+ })
+ }
+
+ resize.check(newWidget.container)
+
+ // restore state
+ stateManager.decrementQueue()
+ if (stateManager.queueCounter === 0) {
+ for (let id in scrollState) {
+ for (let w of widgetManager.getWidgetById(id)) {
+ if (w.scroll) w.scroll(scrollState[id])
+ }
+ }
+ }
+
+ editor.widgetTree.updateTree(editor.selectedWidgets)
+
+ if (editor.selectedWidgets.includes(widget) && !options.preventSelect) {
+ editor.select(newWidget)
+ }
+
+ return newWidget
+
+}
+
+
+var fakeStore = {}
+
+var incrementWidget = function(data, root){
+
+ if (!data) return
+
+ if (root !== false) {
+ fakeStore = {
+ id:[],
+ address:[]
+ }
+ }
+
+ if (Array.isArray(data)) {
+ for (let i in data) {
+ data[i] = incrementWidget(data[i], false)
+ }
+ return data
+ }
+
+ var id = data.id,
+ address = data.address
+
+ if (id && address == '/' + id) {
+
+ data.address = 'auto'
+
+ } else if (address !== 'auto') {
+
+ var addressref
+ while (fakeStore.address.indexOf(address) != -1 || widgetManager.getWidgetByAddress(addressref).length) {
+ address = address.replace(/([0-9]*)$/,function(m){
+ var n = parseInt(m)+1
+ n = isNaN(n)?1:n
+ return n
+ })
+ addressref = widgetManager.createAddressRef(null, data.preArgs,address)
+ }
+
+ fakeStore.address.push(address)
+
+ data.address = address
+
+ }
+
+ if (id) {
+ while (fakeStore.id.indexOf(id) != -1 || widgetManager.getWidgetById(id).length) {
+ id = id.replace(/([0-9]*)$/,function(m){
+ var n = parseInt(m)+1
+ n = isNaN(n)?1:n
+ return n
+ })
+ }
+
+ fakeStore.id.push(id)
+
+ data.id = id
+
+ }
+
+ if (data.widgets && data.widgets.length) {
+ for (let i in data.widgets) {
+ data.widgets[i] = incrementWidget(data.widgets[i], false)
+ }
+ }
+
+ if (data.tabs && data.tabs.length) {
+ for (let i in data.tabs) {
+ data.tabs[i] = incrementWidget(data.tabs[i], false)
+ }
+ }
+
+ return data
+
+}
+
+module.exports = {
+ updateWidget:updateWidget,
+ incrementWidget:incrementWidget
+}
diff --git a/src/client/editor/diff.js b/src/client/editor/diff.js
new file mode 100644
index 00000000..8f2902a9
--- /dev/null
+++ b/src/client/editor/diff.js
@@ -0,0 +1,32 @@
+module.exports = {
+
+ diff: require('jsondiffpatch'),
+
+ diffToWidget: function(widget, diff) {
+
+ // traverse a diff patch and the associated widget
+ // to return the first node (widget and sub-patch) with actual changes
+
+ var children = diff.tabs || diff.widgets
+
+ if (children) {
+ var childrenKeys = Object.keys(children),
+ deletedChildren = childrenKeys.filter(x => typeof x === 'string' && x.match(/_[0-9]+/)),
+ changedChildren = childrenKeys.filter(x => !isNaN(x))
+ }
+
+ if (
+ !children ||
+ Array.isArray(children) || // 'tabs' or 'widgets' property created
+ deletedChildren.length || // 'tabs' or 'widgets' property created
+ changedChildren.length !== 1 || // children reordered (or same property edited in multiple widgets, but case ignored)
+ Array.isArray(children[changedChildren[0]]) // child item created
+ ) {
+ return [widget, diff]
+ }
+
+ return module.exports.diffToWidget(widget.children[changedChildren[0]], children[changedChildren[0]])
+
+ }
+
+}
diff --git a/src/client/editor/index.js b/src/client/editor/index.js
new file mode 100644
index 00000000..18df590b
--- /dev/null
+++ b/src/client/editor/index.js
@@ -0,0 +1,853 @@
+var {updateWidget, incrementWidget} = require('./data-workers'),
+ keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
+ {diff, diffToWidget} = require('./diff'),
+ widgetManager = require('../managers/widgets'),
+ {deepCopy} = require('../utils'),
+ {defaults} = require('../widgets/'),
+ macOs = (navigator.platform || '').match('Mac'),
+ UiSelectArea = require('../ui/ui-selectarea'),
+ UiInspector = require('../ui/ui-inspector'),
+ UiTree = require('../ui/ui-tree'),
+ UiDragResize = require('../ui/ui-dragresize'),
+ notifications = require('../ui/notifications'),
+ locales = require('../locales'),
+ {leftUiSidePanel, rightUiSidePanel} = require('../ui/'),
+ ipc = require('../ipc'),
+ sessionManager
+
+setTimeout(()=>{
+ sessionManager = require('../managers/session/')
+})
+
+const HISTORY_SIZE = 50
+
+class Editor {
+
+ constructor() {
+
+ this.inspector = new UiInspector({selector: '#osc-inspector'})
+ this.inspector.on('update', (event)=>{
+
+ var {propName, value} = event,
+ newWidgets = [],
+ error = false
+
+ for (var w of this.selectedWidgets) {
+
+ let previousValue = w.props[propName]
+
+ if ((propName === 'label' || propName === 'popupLabel') && value === true) {
+ w.props[propName] = 'auto'
+ } else {
+ w.props[propName] = value !== '' ? value : deepCopy(defaults[w.props.type][propName].value)
+ }
+
+ try {
+
+ newWidgets.push(updateWidget(w, {changedProps: [propName], preventSelect: this.selectedWidgets.length > 1}))
+
+ } catch (e) {
+
+ w.props[propName] = previousValue
+ updateWidget(w, {changedProps: [propName], preventSelect: this.selectedWidgets.length > 1})
+
+ notifications.add({
+ class: 'error',
+ message: locales('inspector_error'),
+ duration: 7000
+ })
+ console.error(
+ `Error while setting ${propName} to: ${JSON.stringify(value)}.`,
+ 'It\'s probably a bug, please a new bug ticket with these informations (https://github.com/jean-emmanuel/open-stage-control/issues).'
+ )
+ console.error(e)
+ error = true
+ }
+ }
+
+ if (error) return
+
+ this.pushHistory()
+
+ if (newWidgets.length > 1) this.select(newWidgets)
+
+ })
+
+
+ this.widgetTree = new UiTree({selector: '#osc-tree'})
+ this.widgetTree.on('sorted', (event)=>{
+
+ var {widget, oldIndex, newIndex} = event,
+ propName = widget.props.tabs && widget.props.tabs.length ? 'tabs' : 'widgets'
+
+ if (widget.props[propName].length < 2) return
+
+ widget.props[propName].splice(newIndex, 0, widget.props[propName].splice(oldIndex, 1)[0])
+
+ var indices = [newIndex, oldIndex]
+ if (Math.abs(oldIndex - newIndex) > 1) {
+ for (var i = Math.min(newIndex, oldIndex) + 1; i < Math.max(newIndex, oldIndex); i++) {
+ indices.push(i)
+ }
+ }
+
+ var container = updateWidget(widget, {removedIndexes: indices, addedIndexes: indices, preventSelect: true})
+
+ this.pushHistory({removedIndexes: indices, addedIndexes: indices})
+ this.select(container.children[newIndex])
+
+ })
+
+ this.oscContainer = DOM.get('#osc-container')[0]
+
+
+
+ this.widgetDragResize = new UiDragResize({})
+ this.widgetDragResize.on('move', (e)=>{
+ var left = Math.round(e.left / GRIDWIDTH) * GRIDWIDTH,
+ top = Math.round(e.top / GRIDWIDTH) * GRIDWIDTH
+ var dX = left - e.initLeft,
+ dY = top - e.initTop
+ this.moveWidget(dX, dY)
+ })
+ this.widgetDragResize.on('drag-resize', (e)=>{
+ var width = Math.round(e.width / GRIDWIDTH) * GRIDWIDTH,
+ height = Math.round(e.height / GRIDWIDTH) * GRIDWIDTH
+ var dX = width - e.initWidth,
+ dY = height - e.initHeight
+ this.resizeWidget(dX, dY)
+ })
+
+ this.selectedWidgets = []
+
+ this.clipboard = null
+ this.idClipboard = null
+ ipc.on('clipboard', (data)=>{
+ this.clipboard = data.clipboard
+ this.idClipboard = data.idClipboard
+ })
+
+ this.usePercents = false
+
+ this.enabled = false
+ this.grid = true
+
+ this.unsavedSession = false
+ window.onbeforeunload = ()=>{
+ if (editor.unsavedSession) return true
+ }
+
+ this.history = []
+ this.historyState = -1
+ this.historySession = null
+
+ this.mousePosition = {}
+ this.mouveMoveHandler = this.mouseMove.bind(this)
+ this.mouveLeaveHandler = this.mouseLeave.bind(this)
+
+ keyboardJS.withContext('editing', ()=>{
+
+ var combos = [
+ 'mod + z',
+ 'mod + y',
+ 'mod + shift + z',
+ 'mod + c',
+ 'mod + x',
+ 'mod + v',
+ 'mod + shift + v',
+ macOs ? 'backspace' : 'delete',
+ 'alt + up',
+ 'alt + down',
+ 'alt + right',
+ 'alt + left',
+ 'up',
+ 'down',
+ 'right',
+ 'left',
+ 'mod + shift + a',
+ 'mod + a',
+ 'mod + up',
+ 'mod + down',
+ 'mod + left',
+ 'mod + right',
+ 'f2'
+ ]
+
+ for (let c of combos) {
+ keyboardJS.bind(c, (e)=>{
+ this.handleKeyboard(c, e)
+ })
+ }
+
+ })
+
+ this.selectarea = new UiSelectArea('[data-widget]:not(.not-editable)', (elements)=>{
+
+ elements = elements.map(e => widgetManager.getWidgetByElement(e, ':not(.not-editable)')).filter(e => e)
+
+ for (var i in elements) {
+ this.select(elements[i], {multi:true, fromLasso:true, lassoEnd: i == elements.length - 1})
+ }
+
+ })
+
+
+ }
+
+ handleKeyboard(combo, e){
+
+ if (this.inspector.helpModalOpened || e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT')) return
+
+ e.preventDefault()
+
+ switch (combo) {
+
+ case 'mod + z':
+ this.undo()
+ break
+
+ case 'mod + y':
+ case 'mod + shift + z':
+ this.redo()
+ break
+
+ case 'mod + c':
+ this.copyWidget()
+ break
+
+ case 'mod + x':
+ this.cutWidget()
+ break
+
+ case 'mod + v':
+ this.pasteWidget(this.mousePosition.x, this.mousePosition.y, false)
+ break
+
+ case 'mod + shift + v':
+ this.pasteWidget(this.mousePosition.x, this.mousePosition.y, true)
+ break
+
+ case 'backspace':
+ case 'delete':
+ this.deleteWidget()
+ break
+
+ case 'alt + up':
+ case 'alt + down':
+ case 'alt + right':
+ case 'alt + left':
+ if (!this.selectedWidgets.length) return
+
+ if (this.selectedWidgets[0].props.height === undefined && e.key.match(/Arrow(Up|Down)/)) return
+ if (this.selectedWidgets[0].props.width === undefined && e.key.match(/Arrow(Left|Right)/)) return
+
+ var deltaW = e.key === 'ArrowLeft' ? -GRIDWIDTH : e.key === 'ArrowRight' ? GRIDWIDTH : 0,
+ deltaH = e.key === 'ArrowUp' ? -GRIDWIDTH : e.key === 'ArrowDown' ? GRIDWIDTH : 0
+
+ if (e.shiftKey) {
+ deltaW *= 5
+ deltaH *= 5
+ }
+
+ this.resizeWidget(deltaW, deltaH)
+
+ break
+
+ case 'up':
+ case 'down':
+ case 'right':
+ case 'left':
+ if (!this.selectedWidgets.length) return
+
+ if (this.selectedWidgets[0].props.top === undefined && e.key.match(/Arrow(Up|Down)/)) return
+ if (this.selectedWidgets[0].props.left === undefined && e.key.match(/Arrow(Left|Right)/)) return
+
+ var deltaX = e.key === 'ArrowLeft' ? -GRIDWIDTH : e.key === 'ArrowRight' ? GRIDWIDTH : 0,
+ deltaY = e.key === 'ArrowUp' ? -GRIDWIDTH : e.key === 'ArrowDown' ? GRIDWIDTH : 0
+
+ if (e.shiftKey) {
+ deltaX *= 5
+ deltaY *= 5
+ }
+
+ this.moveWidget(deltaX, deltaY)
+
+ break
+
+ case 'mod + shift + a':
+ if (!this.selectedWidgets.length) return
+ this.unselect()
+ this.selectedWidgets = []
+ this.inspector.clear()
+ break
+
+ case 'mod + a':
+ if (!this.selectedWidgets.length) return
+
+ var curWidget1 = this.selectedWidgets[0]
+
+ if (curWidget1.parent !== widgetManager) {
+ this.select([...curWidget1.parent.children])
+ }
+ break
+
+ case 'mod + up':
+ case 'mod + down':
+ case 'mod + right':
+ case 'mod + left':
+ if (!this.selectedWidgets.length) return
+
+ var curWidget = this.selectedWidgets[0],
+ toSelect = null
+
+ if (e.key === 'ArrowUp' && curWidget.parent !== widgetManager) {
+
+ toSelect = curWidget.parent
+
+ } else if (e.key === 'ArrowDown') {
+
+ let toSelectList = [...curWidget.children]
+
+ if (toSelectList && toSelectList.length) {
+ toSelectList.sort((a,b) => a.container.offsetLeft>b.container.offsetLeft)
+ toSelect = toSelectList[0]
+ if (toSelect.container.classList.contains('not-editable')) {
+ toSelect = null
+ }
+ }
+
+ }
+ else if((e.key == 'ArrowLeft') || (e.key == 'ArrowRight')){
+
+ if (curWidget.parent === widgetManager) return
+
+ let toSelectList = [...curWidget.parent.children]
+
+ if (toSelectList && toSelectList.length) {
+ toSelectList.sort((a,b) => a.container.offsetLeft > b.container.offsetLeft)
+ var idx = toSelectList.indexOf(curWidget)
+ if (idx >= 0) {
+ var nextIdx = (idx + (e.key === 'ArrowLeft' ? -1 : 1 ) + toSelectList.length) % toSelectList.length
+ toSelect = toSelectList[nextIdx]
+ }
+ }
+ }
+
+ if (toSelect) {
+ this.select(toSelect)
+ }
+
+ break
+
+ }
+
+
+ }
+
+ toggleGrid() {
+
+ this.grid = !this.grid
+
+ GRIDWIDTH = this.grid ? 10 : 1
+
+ document.documentElement.style.setProperty('--grid-width', GRIDWIDTH)
+ document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
+
+ }
+
+ enable() {
+
+ if (READ_ONLY || sessionManager.session === null) return
+
+ this.enabled = true
+
+ document.body.classList.add('editor-enabled')
+
+ this.widgetTree.updateTree(this.selectedWidgets)
+
+ leftUiSidePanel.enable()
+ rightUiSidePanel.enable()
+
+ keyboardJS.setContext('editing')
+
+ this.oscContainer.addEventListener('mousemove', this.mouveMoveHandler)
+ this.oscContainer.addEventListener('mouseleave', this.mouveLeaveHandler)
+
+ this.selectarea.enable()
+
+ }
+
+ disable() {
+
+
+ this.unselect()
+ this.selectedWidgets = []
+
+ document.body.classList.remove('editor-enabled')
+
+ keyboardJS.setContext('global')
+
+ this.oscContainer.removeEventListener('mousemove', this.mouveMoveHandler)
+ this.oscContainer.removeEventListener('mouseleave', this.mouveLeaveHandler)
+
+ leftUiSidePanel.disable()
+ rightUiSidePanel.disable()
+ this.widgetTree.clear()
+ this.inspector.clear()
+
+ this.selectarea.disable()
+
+ this.enabled = false
+
+ }
+
+
+ unselect() {
+
+ this.widgetDragResize.clear()
+ this.inspector.clear()
+
+ DOM.each(document, '.editing', (element)=>{
+ element.classList.remove('editing')
+ })
+
+ this.widgetTree.select([])
+
+ }
+
+ select(widget, options={}){
+
+ if (!this.enabled) return
+
+ if (Array.isArray(widget)) {
+
+ this.selectedWidgets = widget
+
+ } else if (options.multi) {
+
+ var sameLevel = false
+
+ while (!sameLevel && widget.parent !== widgetManager) {
+ let test = true
+ if (this.selectedWidgets.length && this.selectedWidgets[0].parent !== widget.parent) test = false
+ sameLevel = test
+ if (!sameLevel) widget = widget.parent
+ }
+
+ if (!this.selectedWidgets.includes(widget) && sameLevel) {
+
+ this.selectedWidgets.push(widget)
+
+ } else if (sameLevel && !options.fromLasso){
+
+ this.selectedWidgets.splice(this.selectedWidgets.indexOf(widget), 1)
+
+ }
+
+ } else {
+
+ this.selectedWidgets = [widget]
+
+ }
+
+ if (options.fromLasso && !options.lassoEnd) return
+
+ this.unselect()
+
+ if (this.selectedWidgets.length > 0) {
+
+ this.inspector.inspect(this.selectedWidgets)
+ this.createSelectionBlock()
+
+ } else {
+
+ this.inspector.clear()
+
+ }
+
+ }
+
+
+ createSelectionBlock(){
+
+ for (let widget of this.selectedWidgets) {
+ DOM.each(document, `[data-widget="${widget.hash}"]`, (item)=>{
+ item.classList.add('editing')
+ })
+ }
+ this.widgetTree.select(this.selectedWidgets)
+ this.widgetDragResize.create(this.selectedWidgets)
+
+ }
+
+ mouseMove(e) {
+
+ this.mousePosition.x = Math.round((e.offsetX + e.target.scrollLeft) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH,
+ this.mousePosition.y = Math.round((e.offsetY + e.target.scrollTop) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH
+
+ }
+
+ mouseLeave(e) {
+
+ this.mousePosition = {}
+
+ }
+
+ copyWidget() {
+
+ if (!this.selectedWidgets.length) return
+ if (this.selectedWidgets[0].getProp('type') === 'root') return
+
+ this.clipboard = deepCopy(this.selectedWidgets.map((w)=>w.props))
+ this.idClipboard = this.selectedWidgets[0].getProp('id')
+
+ ipc.send('clipboard', {
+ clipboard: this.clipboard,
+ idClipboard: this.idClipboard
+ })
+
+ }
+
+ cutWidget() {
+
+ this.copyWidget()
+ this.deleteWidget()
+
+ }
+
+ pasteWidget(x, y, increment) {
+
+ if (!this.selectedWidgets.length || this.clipboard === null) return
+ if (
+ this.selectedWidgets[0].childrenType === undefined ||
+ this.clipboard[0].type === 'tab' && this.selectedWidgets[0].childrenType === 'widget' ||
+ this.clipboard[0].type !== 'tab' && this.selectedWidgets[0].childrenType === 'tab'
+ ) return
+
+ var pastedData = deepCopy(this.clipboard),
+ minTop = Infinity,
+ minLeft = Infinity
+
+ if (increment) {
+ pastedData = incrementWidget(pastedData)
+ }
+
+
+ if (x !== undefined) {
+
+ for (let i in pastedData) {
+
+ let top = pastedData[i].top,
+ left = pastedData[i].left
+
+ if (typeof top === 'string' && top.includes('%')) {
+ top = parseFloat(top) / 100 * this.selectedWidgets[0].widget.offsetHeight
+ pastedData[i]._atop = top
+ pastedData[i]._ptop = true
+ }
+
+ if (typeof left === 'string' && left.includes('%')) {
+ left = parseFloat(left) / 100 * this.selectedWidgets[0].widget.offsetWidth
+ pastedData[i]._aleft = left
+ pastedData[i]._pleft = true
+ }
+
+
+ if (top < minTop) minTop = top
+ if (left < minLeft) minLeft = left
+
+ }
+
+ for (let i in pastedData) {
+
+ if (pastedData[i]._pleft) {
+ pastedData[i].left = ((pastedData[i]._aleft - minLeft + x) * 100 / this.selectedWidgets[0].widget.offsetWidth).toFixed(2) + '%'
+ } else {
+ pastedData[i].left += - minLeft + x
+ }
+
+ if (pastedData[i]._ptop) {
+ pastedData[i].top = ((pastedData[i]._atop - minTop + y) * 100 / this.selectedWidgets[0].widget.offsetHeight).toFixed(2) + '%'
+ } else {
+ pastedData[i].top += - minTop + y
+ }
+
+ }
+
+ }
+
+
+ // paste data
+
+ var store = this.clipboard[0].type === 'tab' ? 'tabs' : 'widgets'
+
+ this.selectedWidgets[0].props[store] = this.selectedWidgets[0].props[store] || []
+ this.selectedWidgets[0].props[store] = this.selectedWidgets[0].props[store].concat(pastedData)
+
+ var indexes = {addedIndexes: []}
+ for (let i = 0; i < pastedData.length; i++) {
+ indexes.addedIndexes.push(this.selectedWidgets[0].props[store].length - 1 - i )
+ }
+
+ updateWidget(this.selectedWidgets[0], indexes)
+
+ this.pushHistory(indexes)
+
+ }
+
+ pasteWidgetAsClone(x, y) {
+
+ if (!this.selectedWidgets.length || this.clipboard === null) return
+ if (!this.idClipboard || !widgetManager.getWidgetById(this.idClipboard).length) return
+
+ if (
+ this.selectedWidgets[0].childrenType === undefined ||
+ this.clipboard[0].type === 'tab' ||
+ this.clipboard[0].type !== 'tab' && this.selectedWidgets[0].childrenType === 'tab'
+ ) return
+
+ var clone = {type: 'clone', widgetId: this.idClipboard},
+ pastedData = deepCopy(this.clipboard)
+
+ clone.width = pastedData[0].width
+ clone.height = pastedData[0].height
+
+
+ if (x !== undefined) {
+
+ clone.left = x
+ clone.top = y
+
+ if (this.usePercents) {
+ clone.top = (100 * y / editor.selectedWidgets[0].widget.offsetHeight).toFixed(2) + '%'
+ clone.left= (100 * x / editor.selectedWidgets[0].widget.offsetWidth).toFixed(2) + '%'
+ }
+
+
+ }
+
+ this.selectedWidgets[0].props.widgets = this.selectedWidgets[0].props.widgets || []
+ this.selectedWidgets[0].props.widgets.push(clone)
+
+ var indexes = {addedIndexes: [this.selectedWidgets[0].props.widgets.length -1]}
+
+ updateWidget(this.selectedWidgets[0], indexes)
+ this.pushHistory(indexes)
+
+ }
+
+
+ deleteWidget() {
+
+ if (!this.selectedWidgets.length) return
+ if (this.selectedWidgets[0].getProp('type') === 'root') return
+
+ var type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
+ parent = this.selectedWidgets[0].parent,
+ index = this.selectedWidgets.map(w => parent.children.indexOf(w)).sort((a,b)=>{return b-a}),
+ removedIndexes = []
+
+ if (type === 'widget') {
+ for (let i of index) {
+ removedIndexes.push(i)
+ parent.props.widgets.splice(i,1)
+ }
+ } else {
+ for (let i of index) {
+ removedIndexes.push(i)
+ parent.props.tabs.splice(i,1)
+ }
+ }
+
+ var container = updateWidget(parent, {preventSelect: true, removedIndexes})
+ if (container.children.length) {
+ this.select(container.children[Math.min(index.pop(), container.children.length - 1)])
+ } else {
+ this.select(container)
+ }
+ this.pushHistory({removedIndexes})
+
+ }
+
+ resizeWidget(deltaW, deltaH, ui) {
+
+ if (!this.selectedWidgets.length) return
+
+ var newWidgets = []
+
+ for (var i = 0; i < this.selectedWidgets.length; i++) {
+
+ let w = this.selectedWidgets[i],
+ nW, nH
+
+ if (i === 0 && ui) {
+ nW = ui.originalSize.width + deltaW
+ nH = ui.originalSize.height + deltaH
+
+ } else {
+ nW = w.container.offsetWidth + deltaW
+ nH = w.container.offsetHeight + deltaH
+ }
+
+ if (w.props.width !== undefined && w.parent.getProp('layout') !== 'vertical') {
+ var newWidth = Math.max(nW, GRIDWIDTH) / PXSCALE
+ if (typeof w.props.width === 'string' && w.props.width.indexOf('%') > -1) {
+ w.props.width = (100 * PXSCALE * newWidth / w.container.parentNode.offsetWidth).toFixed(2) + '%'
+ } else {
+ w.props.width = newWidth
+ }
+ }
+
+ if (w.props.height !== undefined && w.parent.getProp('layout') !== 'horizontal') {
+ var newHeight = Math.max(nH, GRIDWIDTH) / PXSCALE
+ if (typeof w.props.height === 'string' && w.props.height.indexOf('%') > -1) {
+ w.props.height = (100 * PXSCALE * newHeight / w.container.parentNode.offsetHeight).toFixed(2) + '%'
+ } else {
+ w.props.height = newHeight
+ }
+ }
+
+ if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {changedProps: ['width', 'height'], preventSelect: this.selectedWidgets.length > 1}))
+
+ }
+
+ this.pushHistory()
+
+ if (newWidgets.length > 1) this.select(newWidgets, {preventSelect: this.selectedWidgets.length > 1})
+
+ }
+
+ moveWidget(deltaX, deltaY) {
+
+ if (!this.selectedWidgets.length) return
+
+ var newWidgets = []
+
+ for (var w of this.selectedWidgets) {
+
+ var newTop = Math.max(parseInt(w.container.offsetTop) / PXSCALE + deltaY, 0)
+ if (typeof w.props.top === 'string' && w.props.top.indexOf('%') > -1) {
+ w.props.top = (100 * PXSCALE * newTop / w.container.parentNode.offsetHeight).toFixed(2) + '%'
+ } else {
+ w.props.top = newTop
+ }
+ var newLeft = Math.max(parseInt(w.container.offsetLeft) / PXSCALE + deltaX, 0)
+ if (typeof w.props.left === 'string' && w.props.left.indexOf('%') > -1) {
+ w.props.left = (100 * PXSCALE * newLeft / w.container.parentNode.offsetWidth).toFixed(2) + '%'
+ } else {
+ w.props.left = newLeft
+ }
+
+ newWidgets.push(updateWidget(w, {changedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
+
+ }
+
+ this.pushHistory()
+
+ if (newWidgets.length > 1) this.select(newWidgets)
+
+ }
+
+
+
+ pushHistory(indexes) {
+
+ this.unsavedSession = true
+
+ if (this.historyState > -1) {
+ this.history.splice(0, this.historyState + 1)
+ this.historyState = -1
+ }
+
+ var d = diff.diff(this.historySession, sessionManager.session.getRoot())
+
+ if (d) {
+ diff.patch(this.historySession, deepCopy(d))
+ this.history.unshift([deepCopy(d), indexes])
+ if (this.history.length > HISTORY_SIZE) this.history.pop()
+ }
+
+ }
+
+ clearHistory() {
+
+ this.history = []
+ this.historyState = -1
+ this.historySession = deepCopy(sessionManager.session.getRoot())
+
+ }
+
+ undo() {
+
+ if (this.historyState === this.history.length - 1) return
+
+ this.historyState += 1
+
+ var [patch, indexes] = this.history[this.historyState],
+ d1 = deepCopy(patch),
+ d2 = deepCopy(patch)
+
+ diff.unpatch(this.historySession, d1)
+ diff.unpatch(sessionManager.session.getRoot(), d2)
+
+ this.updateWidgetFromPatch(patch, indexes ? {
+ addedIndexes: deepCopy(indexes.removedIndexes),
+ removedIndexes: deepCopy(indexes.addedIndexes),
+ } : undefined)
+
+ }
+
+ redo() {
+
+ if (this.historyState === -1) return
+
+ var [patch, indexes] = this.history[this.historyState],
+ d1 = deepCopy(patch),
+ d2 = deepCopy(patch)
+
+ diff.patch(this.historySession, d1)
+ diff.patch(sessionManager.session.getRoot(), d2)
+
+ this.updateWidgetFromPatch(patch, indexes ? {
+ addedIndexes: deepCopy(indexes.addedIndexes),
+ removedIndexes: deepCopy(indexes.removedIndexes),
+ } : undefined)
+
+ this.historyState -= 1
+
+ }
+
+ updateWidgetFromPatch(patch, indexes) {
+
+ var [widget, subpatch] = diffToWidget(widgetManager.getWidgetById('root')[0], patch),
+ options = {}
+
+ if (indexes) {
+ options = {...indexes}
+ } else {
+ options.changedProps = Object.keys(subpatch)
+ options.reuseChildren = false
+ }
+
+ updateWidget(widget, options)
+
+ if (this.selectedWidgets[0] && !widgetManager.widgets[this.selectedWidgets[0].hash]) {
+ this.unselect()
+ this.selectedWidgets = []
+ this.inspector.clear()
+ } else if (this.selectedWidgets[0]) {
+ this.widgetDragResize.create(this.selectedWidgets)
+ }
+
+ }
+
+
+
+
+}
+
+var editor = new Editor()
+
+module.exports = editor
+
+require('./context-menu')
diff --git a/src/client/events/click.js b/src/client/events/click.js
new file mode 100644
index 00000000..0a9bc274
--- /dev/null
+++ b/src/client/events/click.js
@@ -0,0 +1,66 @@
+const iOS = require('../ui/ios')
+const macOs = (navigator.platform || '').match('Mac')
+
+var longTouchTimer = false,
+ clearLongTouchTimer = function() {
+ if (longTouchTimer) {
+ clearTimeout(longTouchTimer)
+ longTouchTimer = false
+ }
+ }
+
+if (macOs) {
+ // on macOs, ctrl+click generates a contextmenu event
+ // that should be interpreted as a rightclick
+ document.body.addEventListener('contextmenu', (event)=>{
+ event.preventDefault()
+ DOM.dispatchEvent(event.target, 'fast-right-click', event)
+ })
+} else {
+ document.body.setAttribute('oncontextmenu', 'return false')
+}
+
+function mouseToFastClick(event) {
+
+ if (event.pointerType === 'touch') return
+ if (event.button == 2) event.preventDefault()
+
+ var e = event
+
+ var name = event.button == 2 ? 'fast-right-click' : 'fast-click'
+
+ DOM.dispatchEvent(e.target, name, e)
+
+}
+
+function touchToFastClick(event) {
+
+ var e = event.changedTouches[0]
+
+ e.shiftKey = event.shiftKey
+ e.ctrlKey = event.ctrlKey
+
+ DOM.dispatchEvent(e.target, 'fast-click', e)
+
+ if (e.preventOriginalEvent) event.preventDefault()
+
+ longTouchTimer = setTimeout(()=>{
+
+ var off = DOM.offset(e.target)
+
+ e.offsetX = e.pageX - off.left
+ e.offsetY = e.pageY - off.top
+
+ DOM.dispatchEvent(e.target, 'fast-right-click', e)
+
+ clearLongTouchTimer()
+
+ }, 600)
+
+}
+
+if (!iOS) document.addEventListener('pointerdown', mouseToFastClick, true)
+document.addEventListener('touchstart', touchToFastClick, {passive: false, capture: true})
+
+
+DOM.addEventListener(document, 'touchend touchmove touchcancel', clearLongTouchTimer)
diff --git a/src/client/events/double-click.js b/src/client/events/double-click.js
new file mode 100644
index 00000000..cba97f49
--- /dev/null
+++ b/src/client/events/double-click.js
@@ -0,0 +1,43 @@
+module.exports = (element, callback, options={})=>{
+
+ var lastTapTime = 0,
+ lastTapX,
+ lastTapY
+
+ element.addEventListener(options.click ? 'click' : 'fast-click', (event)=>{
+
+ if (event.capturedByEditor && !options.ignoreEditorCapture) return
+
+ var tapTime = Date.now(),
+ tapLength = tapTime - lastTapTime,
+ eventData = options.click ? event : event.detail
+
+ if (
+
+ tapLength < DOUBLE_TAP_TIME &&
+ Math.abs(lastTapX - eventData.pageX) < 20 &&
+ Math.abs(lastTapY - eventData.pageY) < 20 &&
+ (!options.click || event.pageX !== 0) // prevent fake click emitted with keyboard focus events
+
+ ) {
+
+ // execute callback at next cycle to ensure draginit events are resolved first
+ setTimeout(()=>{
+ callback(event.detail)
+ }, 0)
+ lastTapTime = 0
+
+ // prevent touchend
+ if (!options.click) event.detail.preventOriginalEvent = true
+
+ } else {
+
+ lastTapTime = tapTime
+ lastTapX = eventData.pageX
+ lastTapY = eventData.pageY
+
+ }
+
+ })
+
+}
diff --git a/src/client/events/drag.js b/src/client/events/drag.js
new file mode 100644
index 00000000..ce403607
--- /dev/null
+++ b/src/client/events/drag.js
@@ -0,0 +1,331 @@
+const {normalizeDragEvent, resetEventOffset, TRAVERSING_SAMEWIDGET} = require('./utils')
+const iOS = require('../ui/ios')
+
+var targets = {},
+ previousPointers = {}
+
+function pointerDownHandler(event) {
+
+ if (event.capturedByEditor || event.touchPunch) return
+
+ if (!event.multitouch) {
+ for (var i in targets) {
+ if (targets[i] == event.target) return
+ }
+ }
+
+ event = normalizeDragEvent(event)
+
+ if (event.traversingStack) {
+
+ event.target = event.target.closest('.drag-event')
+
+ var widget = event.target.closest('.drag-event')._drag_widget,
+ local = event.traversingStack.stack[event.traversingStack.stack.length - 1]
+
+ if (widget.getProp) event.traversingStack.firstType = widget.getProp('type')
+
+ if (local.mode === TRAVERSING_SAMEWIDGET && local.type && local.type !== event.traversingStack.firstType) {
+ event.traversing = false
+ } else {
+ event.traversing = true
+ }
+
+ }
+
+ targets[event.pointerId] = event.target
+ previousPointers[event.pointerId] = event
+
+ triggerWidgetEvent(targets[event.pointerId], 'draginit', event)
+
+}
+
+function pointerMoveHandler(event) {
+
+ event = normalizeDragEvent(event, previousPointers[event.pointerId])
+
+ event.stopPropagation = true
+
+ if (event.traversing) {
+
+ var previousTarget = targets[event.pointerId],
+ target = event.isTouch ?
+ document.elementFromPoint(event.clientX, event.clientY)
+ : event.target
+
+ if (target) target = target.closest('.drag-event')
+
+ var local = null
+ if (target && event.traversingStack) {
+ for (var i = event.traversingStack.stack.length - 1; i > -1; i--) {
+ if (event.traversingStack.stack[i].container.contains(target)) {
+ local = event.traversingStack.stack[i]
+ break
+ }
+ }
+ if (!local) {
+ target = null
+ } else if (local.mode === TRAVERSING_SAMEWIDGET && local.type) {
+ var widget = target.closest('.drag-event')._drag_widget
+ if (widget.getProp && local.type !== widget.getProp('type')) target = null
+ }
+ }
+
+
+
+
+ if (target && event.isTouch) {
+ resetEventOffset(event, target)
+ }
+
+ if (previousTarget !== target) {
+ triggerWidgetEvent(previousTarget, 'dragend', event)
+ }
+
+
+ if (target && event.traversing) {
+ triggerWidgetEvent(target, previousTarget !== target ? 'draginit' : 'drag', event)
+ }
+
+ targets[event.pointerId] = target
+
+
+ } else {
+ triggerWidgetEvent(targets[event.pointerId], 'drag', event)
+ }
+
+ previousPointers[event.pointerId] = event
+
+}
+
+function pointerUpHandler(event) {
+
+ event = normalizeDragEvent(event, previousPointers[event.pointerId])
+
+ triggerWidgetEvent(targets[event.pointerId], 'dragend', event)
+
+ delete targets[event.pointerId]
+ delete previousPointers[event.pointerId]
+
+}
+
+
+// Move / Up Filter
+
+function pointerMoveFilter(event) {
+
+ if (targets[event.pointerId] !== undefined) {
+ pointerMoveHandler.call(targets[event.pointerId], event)
+ }
+
+}
+
+function pointerUpFilter(event) {
+
+ if (targets[event.pointerId] !== undefined) {
+ pointerUpHandler.call(targets[event.pointerId], event)
+ delete targets[event.pointerId]
+ }
+
+}
+
+// Mouse events wrappers
+
+function mouseMultiWrapper(event) {
+ mouseDownCapture(event, true)
+}
+
+function mouseDownCapture(event, multitouch) {
+ if (event.pointerType === 'touch') return
+ // event.pointerId = 'mouse'
+ event.multitouch = multitouch
+ pointerDownHandler(event)
+}
+
+function mouseMoveCapture(event) {
+ if (event.pointerType === 'touch') return
+ // event.pointerId = 'mouse'
+ event.inertia = event.ctrlKey ? 10 : 1
+ pointerMoveFilter(event)
+}
+
+function mouseUpCapture(event){
+ if (event.pointerType === 'touch') return
+ // event.pointerId = 'mouse'
+ pointerUpFilter(event)
+}
+
+
+// Touch events wrappers
+
+function touchMultiWrapper(event) {
+ touchDownCapture(event, true)
+}
+
+function touchDownCapture(event, multitouch) {
+
+ event.preventDefault()
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+
+ if (event.traversingStack) {
+ touchEvent.traversingStack = event.traversingStack
+ }
+
+ touchEvent.pointerId = touchEvent.identifier
+ touchEvent.multitouch = multitouch
+
+ pointerDownHandler(touchEvent)
+ }
+}
+
+function touchMoveCapture(event) {
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+
+ var fingers = 0
+ for (var j in event.touches) {
+ if (event.touches[j].target && event.touches[j].target.isSameNode(touchEvent.target)) {
+ fingers += 1
+ if (fingers == 2) {
+ touchEvent.inertia = 10
+ break
+ }
+ }
+ }
+
+ touchEvent.pointerId = touchEvent.identifier
+ pointerMoveFilter(touchEvent)
+ }
+}
+
+function touchUpCapture(event) {
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+ touchEvent.pointerId = touchEvent.identifier
+ pointerUpFilter(touchEvent)
+ }
+}
+
+// Callback trigger
+
+function triggerWidgetEvent(target, name, event) {
+ if (target !== null && target._drag_widget) {
+ target._drag_widget.trigger(name, event)
+ } else if (target !== null) {
+ triggerWidgetEvent(target.closest('.drag-event'), name, event)
+ }
+}
+
+// init
+
+DOM.ready(()=>{
+ if (!iOS) document.addEventListener('pointermove', mouseMoveCapture, true)
+ if (!iOS) document.addEventListener('pointerup', mouseUpCapture, true)
+ document.addEventListener('touchmove', touchMoveCapture, true)
+ DOM.addEventListener(document, 'touchend touchcancel', touchUpCapture, true)
+
+})
+
+module.exports = {
+
+ setup: function(options) {
+
+ if (
+ this._customBindings['drag'] !== 0 ||
+ this._customBindings['draginit'] !== 0 ||
+ this._customBindings['dragend'] !== 0 ||
+ !options || options.ignoreCustomBindings
+ ) {
+ return
+ }
+
+ var {element, multitouch} = options
+
+ element._drag_widget = this
+ element.style.touchAction = 'none'
+ element.classList.add('drag-event')
+
+ if (multitouch) {
+ element.addEventListener('touchstart', touchMultiWrapper, false)
+ if (!iOS) element.addEventListener('pointerdown', mouseMultiWrapper)
+ } else {
+ element.addEventListener('touchstart', touchDownCapture, false)
+ if (!iOS) element.addEventListener('pointerdown', mouseDownCapture)
+ }
+
+ },
+
+ teardown: function(options) {
+
+ if (
+ this._customBindings['drag'] !== 0 ||
+ this._customBindings['draginit'] !== 0 ||
+ this._customBindings['dragend'] !== 0 ||
+ !options || options.ignoreCustomBindings
+ ) {
+ return
+ }
+
+ var {element, multitouch} = options
+
+ delete element._drag_widget
+ element.style.touchAction = ''
+ element.classList.remove('drag-event')
+
+ if (multitouch) {
+ element.removeEventListener('touchstart', touchMultiWrapper, false)
+ if (!iOS) element.removeEventListener('pointerdown', mouseMultiWrapper)
+ } else {
+ element.removeEventListener('touchstart', touchDownCapture, false)
+ if (!iOS) element.removeEventListener('pointerdown', mouseDownCapture)
+ }
+
+ },
+
+ enableTraversingGestures: function(element, options={}) {
+
+ if (element._traversing) return
+
+ var traversing = options.type ? TRAVERSING_SAMEWIDGET : true,
+ traversingType = options.type === 'auto' ? '' : options.type
+
+ element._traversing = traversing
+
+ function makeEventTraversing(event) {
+ if (event.ctrlKey) return
+ if (!event.traversingStack) event.traversingStack = {firstType: '', stack: []}
+ event.traversingStack.stack.push({
+ container: element,
+ mode: traversing,
+ type: traversingType
+ })
+
+ }
+
+ if (!iOS) element.addEventListener('pointerdown', makeEventTraversing, true)
+ element.addEventListener('touchstart', makeEventTraversing, true)
+
+ element.addEventListener('disableTraversingGestures', (e)=>{
+ e.stopPropagation()
+ if (!iOS) element.removeEventListener('pointerdown', makeEventTraversing, true)
+ element.removeEventListener('touchstart', makeEventTraversing, true)
+
+ })
+
+ },
+
+ disableTraversingGestures: function(element) {
+
+ if (!element._traversing) return
+
+ delete element._traversing
+
+ DOM.dispatchEvent(element, 'disableTraversingGestures')
+
+ }
+
+}
diff --git a/src/client/events/event-emitter.js b/src/client/events/event-emitter.js
new file mode 100644
index 00000000..1cdffd61
--- /dev/null
+++ b/src/client/events/event-emitter.js
@@ -0,0 +1,128 @@
+var customEvents = {}
+setTimeout(()=>{
+ customEvents['draginit'] = customEvents['drag'] = customEvents['dragend'] = require('./drag')
+ customEvents['resize'] = require('./resize')
+})
+
+// micro optimisation from eventemitter3
+var has = Object.prototype.hasOwnProperty
+
+module.exports = class EventEmitter {
+
+ constructor() {
+
+ this._customBindings = {}
+ this._listeners = {}
+
+ for (var evt in customEvents) {
+ this._customBindings[evt] = 0
+ }
+
+ }
+
+ trigger(evt, data) {
+
+ if (has.call(this._listeners, evt)) {
+ // shallow copy in case a listener gets added/removed while looping
+ var listeners = this._listeners[evt].slice(0)
+ for (var i = 0, len = listeners.length; i !== len; i++) {
+ listeners[i](data)
+ }
+ }
+
+ // Event bubbling
+ if (!data || !data.stopPropagation) {
+ if (this.parent) this.parent.trigger(evt, data)
+ }
+
+ return this
+
+ }
+
+ on(evt, listener, options) {
+
+ if (options) {
+
+ // Custom event setup
+ if (has.call(customEvents, evt)) {
+ this._customBindings[evt]
+ if (this._customBindings[evt] === 0) {
+ listener._options = options
+ customEvents[evt].setup.call(this, options)
+ }
+ this._customBindings[evt]++
+ }
+
+ // Context storing
+ if (options.context) listener._context = options.context
+
+ }
+
+ // Add listener
+ if (!has.call(this._listeners, evt)) this._listeners[evt] = []
+
+ var listeners = this._listeners[evt]
+
+ if (listeners.indexOf(listener) === -1) listeners.push(listener)
+
+ return this
+
+ }
+
+ off(evt, listener, context) {
+
+ // Remove listener
+ if (evt && has.call(this._listeners, evt)) {
+
+ var listeners = this._listeners[evt]
+
+ if (listener) {
+
+ var index = listeners.indexOf(listener)
+
+ if (index !== -1) {
+
+ if (context && context !== listener._context) return this
+
+ listeners.splice(index, 1)
+
+ // Custom event teardown
+ if (has.call(customEvents, evt)) {
+
+ if (this._customBindings[evt] !== 0) {
+ this._customBindings[evt]--
+ if (this._customBindings[evt] === 0) {
+ customEvents[evt].teardown.call(this, listener._options)
+ delete listener._options
+ }
+ }
+
+ }
+
+ }
+
+ } else {
+
+ for (var i = listeners.length - 1; i !== -1; i--) {
+
+ if (!context || context == listeners[i]._context) {
+ this.off(evt, listeners[i], context)
+ }
+
+ }
+
+ }
+
+ } else if (!evt) {
+
+ for (var k in this._listeners) {
+ this.off(k, undefined, context)
+ }
+
+ }
+
+ return this
+
+ }
+
+}
diff --git a/src/client/events/resize.js b/src/client/events/resize.js
new file mode 100644
index 00000000..f7cf8f9a
--- /dev/null
+++ b/src/client/events/resize.js
@@ -0,0 +1,64 @@
+var elements = []
+
+function checkResizes(context, force){
+ // Iterate over all elements to which the 'resize' event is bound.
+ var resizedElems = [],
+ cachedStyles = []
+ for (let i = elements.length - 1; i >= 0; i--) {
+ var elem = elements[i]
+
+ if (!context.contains(elem)) continue
+
+ var style = window.getComputedStyle(elem),
+ width = parseInt(style['width']) - parseInt(style['padding-left']) - parseInt(style['padding-right']),
+ height = parseInt(style['height']) - parseInt(style['padding-top']) - parseInt(style['padding-bottom'])
+
+ if (!width || !height) continue
+
+ // If element size has changed since the last time, update the element
+ // data store and trigger the 'resize' event.
+ if (force || width != elem.resizedataw || height != elem.resizedatah) {
+ elem.resizedataw = width
+ elem.resizedatah = height
+ resizedElems.push(elem)
+ cachedStyles.push(style)
+ }
+ }
+ for (let i = resizedElems.length - 1; i >= 0; i--) {
+ resizedElems[i]._resize_widget.trigger('resize', {
+ width: resizedElems[i].resizedataw,
+ height: resizedElems[i].resizedatah,
+ style:cachedStyles[i],
+ stopPropagation: true
+ })
+ }
+
+}
+
+window.addEventListener('resize', ()=>{checkResizes(document)})
+
+module.exports = {
+
+ setup: function(options) {
+
+ if (!options) return
+ if (elements.indexOf(options.element) == -1) {
+ elements.push(options.element)
+ options.element._resize_widget = this
+ }
+
+ },
+ teardown: function(options) {
+
+ if (!options) return
+
+ if (elements.indexOf(options.element) != -1) {
+ elements.splice(elements.indexOf(options.element), 1)
+ delete options.element._resize_widget
+ }
+
+ },
+
+ check: checkResizes
+
+}
diff --git a/src/client/events/transform-coords.js b/src/client/events/transform-coords.js
new file mode 100644
index 00000000..5425ac7d
--- /dev/null
+++ b/src/client/events/transform-coords.js
@@ -0,0 +1,52 @@
+/*
+
+ Adapted from https://gist.github.com/Yaffle/1145197#file-convertpointfrompagetonode-js
+
+ Disabled for now
+
+*/
+
+
+var I = new WebKitCSSMatrix()
+
+function Point(x, y, z) {
+ this.x = x
+ this.y = y
+ this.z = z
+}
+
+Point.prototype.transformBy = function(matrix) {
+ var tmp = matrix.multiply(I.translate(this.x, this.y, this.z))
+ return new Point(tmp.m41, tmp.m42, tmp.m43)
+}
+
+function getTransformationMatrix(w) {
+
+ var transformationMatrix = I,
+ node = w
+
+ while (node) {
+ if (node._ignore_css_transforms) break
+ if (node._drag_widget) {
+
+ var transform = node._drag_widget.cssTransform || 'none',
+ c = transform === 'none' ? I : new WebKitCSSMatrix(transform)
+
+ transformationMatrix = c.multiply(transformationMatrix)
+
+ }
+ node = node.parentNode
+
+ }
+
+ transformationMatrix = I.multiply(transformationMatrix)
+
+ return transformationMatrix
+
+}
+
+module.export = function cssTransformCoords(node, x, y) {
+
+ return new Point(pageX, pageY, 0).transformBy(getTransformationMatrix(element).inverse())
+
+}
diff --git a/src/client/events/utils.js b/src/client/events/utils.js
new file mode 100644
index 00000000..d6a3d944
--- /dev/null
+++ b/src/client/events/utils.js
@@ -0,0 +1,106 @@
+const Touch = window.Touch || class Touch {}
+// const cssTransformCoords = require('./transform-coords')
+
+
+module.exports = {
+
+ fix: function(e) {
+
+ return {
+
+ target: e.target,
+ firstTarget: null,
+ offsetX: e.offsetX,
+ offsetY: e.offsetY,
+ pageX: e.pageX,
+ pageY: e.pageY,
+ clientX: e.clientX,
+ clientY: e.clientY,
+ movementX: e.movementX,
+ movementY: e.movementY,
+ pointerId: e.pointerId,
+ pointerType: e.pointerType,
+ button: e.button,
+ ctrlKey: e.ctrlKey,
+ shiftKey: e.shiftKey,
+ inertia: e.multitouch ? 1 : e.inertia,
+ traversing: e.traversing,
+ traversingStack: e.traversingStack,
+ multitouch: e.multitouch,
+ isTouch: e instanceof Touch
+ }
+ },
+
+ normalizeDragEvent: function(event, previousEvent) {
+
+ event = module.exports.fix(event)
+
+ event.firstTarget = previousEvent ? previousEvent.firstTarget : event.target
+
+ if (event.movementX === undefined) {
+
+ event.movementX = previousEvent ? event.pageX - previousEvent.pageX : 0
+ event.movementY = previousEvent ? event.pageY - previousEvent.pageY : 0
+
+ }
+
+ if (event.isTouch && !previousEvent) {
+
+ module.exports.resetEventOffset(event, event.target)
+
+ } else if (event.isTouch && previousEvent) {
+
+ event.offsetX = previousEvent.offsetX + event.movementX
+ event.offsetY = previousEvent.offsetY + event.movementY
+
+ }
+
+ if (event.inertia === undefined) {
+
+ event.inertia = 1
+
+ }
+
+ if (previousEvent) {
+
+ if (previousEvent.traversing) event.traversing = previousEvent.traversing
+ if (previousEvent.traversingStack) event.traversingStack = previousEvent.traversingStack
+
+ if (previousEvent.multitouch) {
+ event.multitouch = previousEvent.multitouch
+ event.inertia = 1
+ }
+
+ }
+
+
+ // if (!event.traversing) {
+ // // css transfom fix (doesn't work well with traversing gestures)
+ // var transformedCoords = cssTransformCoords(event.firstTarget, event.movementX, event.movementY)
+ // event.movementX = transformedCoords.x
+ // event.movementY = transformedCoords.y
+ // }
+
+ return event
+
+ },
+
+ resetEventOffset: function(event, target) {
+
+ var off = DOM.offset(target)
+
+ event.offsetX = event.pageX - off.left
+ event.offsetY = event.pageY - off.top
+
+ // if (!event.traversing) {
+ // // css transfom fix (doesn't work well with traversing gestures)
+ // var transformedCoords = cssTransformCoords(event.firstTarget, event.offsetX, event.offsetY)
+ // event.offsetX = transformedCoords.x
+ // event.offsetY = transformedCoords.y
+ // }
+
+ },
+
+ TRAVERSING_SAMEWIDGET: 1
+
+}
diff --git a/src/client/globals.js b/src/client/globals.js
new file mode 100644
index 00000000..e23cf22c
--- /dev/null
+++ b/src/client/globals.js
@@ -0,0 +1,31 @@
+window.IP = window.IP || ''
+window.ENV = window.ENV || {}
+location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, (s,k,v)=>{
+ ENV[k]=v
+})
+
+window.LANG = ENV.lang === 'debug' ? 'debug' : (ENV.lang || navigator.language || '').substr(0, 2).toLowerCase()
+
+window.PACKAGE = require('../../package.json')
+
+window.LOADING = null
+
+window.READ_ONLY = window.READ_ONLY || false
+window.GRIDWIDTH = 10
+
+
+window.ELECTRON_NOGPU = false
+window.CANVAS_FRAMERATE = parseFloat(ENV.framerate || 60)
+window.CANVAS_SCALING = parseFloat(ENV.forceHdpi) || ( ENV.hdpi ? window.devicePixelRatio : 1 )
+window.INITIALZOOM = ENV.zoom ? parseFloat(ENV.zoom) : 1
+window.PXSCALE = INITIALZOOM
+document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+
+window.DOUBLE_TAP_TIME = ENV.doubletap ? parseInt(ENV.doubletap) : 375
+
+
+window.JSON.parseFlex = require('json5').parse
+
+window.DOM = require('./dom')
+
+window.TITLE = PACKAGE.productName + ' v' + PACKAGE.version
diff --git a/src/client/index.js b/src/client/index.js
new file mode 100644
index 00000000..bf932fbf
--- /dev/null
+++ b/src/client/index.js
@@ -0,0 +1,39 @@
+document.addEventListener('DOMContentLoaded', function(event) {
+
+ require('./globals')
+ require('./stacktrace')
+
+ var locales = require('./locales'),
+ html = require('nanohtml')
+
+ DOM.get(document, '#osc-greeting-header')[0].appendChild(html`${PACKAGE.productName} v${PACKAGE.version} `)
+
+ DOM.init()
+
+ var uiLoading = require('./ui/ui-loading')
+ uiLoading(locales('loading_server'))
+
+ setTimeout(()=>{
+
+ var ipc = require('./ipc/'),
+ backup = require('./backup')
+
+ ipc.init()
+
+
+ require('./ui/init')
+
+ document.title = TITLE
+
+ ipc.send('open', {hotReload: backup.exists})
+
+ window.onunload = ()=>{
+ ipc.send('close')
+ }
+
+ backup.load()
+
+
+ }, 100)
+
+})
diff --git a/src/client/ipc/callbacks.js b/src/client/ipc/callbacks.js
new file mode 100644
index 00000000..ba881fbd
--- /dev/null
+++ b/src/client/ipc/callbacks.js
@@ -0,0 +1,129 @@
+var utils = require('../ui/utils'),
+ osc = require('../osc'),
+ session = require('../managers/session/'),
+ widgetManager = require('../managers/widgets'),
+ state = require('../managers/state'),
+ editor = require('../editor/'),
+ locales = require('../locales'),
+ UiModal = require('../ui/ui-modal'),
+ uiLoading = require('../ui/ui-loading'),
+ notifications = require('../ui/notifications'),
+ raw = require('nanohtml/raw'),
+ backup = require('../backup')
+
+module.exports = {
+
+ bundle: function(data) {
+ for (let i in data) {
+ osc.receive(data[i])
+ }
+ },
+
+ receiveOsc: function(data){
+ osc.receive(data)
+ },
+
+ connected:function(){
+ uiLoading(false)
+ },
+
+ sessionOpen: function(data){
+
+ session.open(data)
+
+ },
+
+ sessionNew: function(){
+
+ session.create()
+
+ },
+
+ sessionSaved: function(data){
+
+ editor.unsavedSession = false
+
+ },
+
+ stateLoad: function(data){
+
+ state.load(data.state, data.send, data.path)
+
+ },
+
+ stateSend:function(){
+ notifications.add({
+ icon: 'wifi',
+ message: locales('loading_newclient')
+ })
+
+ setTimeout(function(){
+
+ osc.syncOnly = true
+ state.send()
+ osc.syncOnly = false
+
+ },200)
+
+ },
+
+ editorDisable: function(data){
+
+ editor.disable(data.permanent)
+
+ },
+
+ error: function(data){
+ new UiModal({title: raw(utils.icon('exclamation-triangle') + ' ' + locales('error')), content: raw(data), closable:true})
+ },
+
+ reloadCss: function(){
+ var queryString = '?reload=' + Date.now()
+ DOM.each(document, 'link[rel="stylesheet"][hot-reload]', (el)=>{
+ el.href = el.href.replace(/\?.*|$/, queryString)
+ })
+
+ setTimeout(()=>{
+ var root = widgetManager.getWidgetById('root')[0]
+ if (root) root.onPropChanged('color')
+ GRIDWIDTH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
+ },200)
+
+
+ },
+
+ reload: function(){
+
+ backup.save()
+ editor.unsavedSession = false
+ window.location.href = window.location.href
+
+ },
+
+ notify: function(data) {
+
+ var message = data.message || ''
+
+ if (data.locale) message = locales(data.locale) + message
+
+ notifications.add({
+ icon: data.icon,
+ class: data.class,
+ message: message
+ })
+
+ },
+
+ setTitle: function(data) {
+
+ document.title = TITLE + (data ? ' (' + data + ')' : '')
+
+ },
+
+ serverTargets: function(data) {
+
+ if (data) osc.serverTargets = data
+
+ }
+
+}
diff --git a/src/client/ipc/index.js b/src/client/ipc/index.js
new file mode 100644
index 00000000..12c91bc5
--- /dev/null
+++ b/src/client/ipc/index.js
@@ -0,0 +1,185 @@
+var EventEmitter = require('../events/event-emitter'),
+ cache = require('../managers/cache'),
+ nanoid = require('nanoid/generate'), uuid,
+ notifications,
+ locales
+
+var localUuid = ENV.id || cache.get('osc.uuid', false)
+if (localUuid) {
+ uuid = localUuid
+} else {
+ uuid = nanoid('0123456789abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10)
+ cache.set('uuid', uuid, false)
+}
+
+setTimeout(()=>{
+ notifications = require('../ui/notifications')
+ locales = require('../locales')
+})
+
+var reconnectTimeout = 2000,
+ hearbeatInterval = 5000,
+ hearbeatTimeout = 3000,
+ protocol = document.location.protocol === 'https:' ? 'wss://' : 'ws://'
+
+class Ipc extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.socket = null
+
+ this.queue = []
+
+ this.disconnected = false
+ this.reconnect = undefined
+
+ this.hearbeat = undefined
+ this.hearbeatTimeout = undefined
+ this.on('pong', ()=>{
+ clearTimeout(this.hearbeatTimeout)
+ })
+ this.on('ping', ()=>{
+ this.socket.send('["pong"]')
+ })
+
+ document.cookie = 'client_id=' + uuid
+
+ try {
+ this.open()
+ } catch(e) {
+ console.warn('Could not open a WebSocket connection')
+ console.log(e)
+ }
+
+
+ }
+
+ init() {
+
+ var callbacks = require('./callbacks')
+
+ for (let i in callbacks) {
+ let callback = callbacks[i]
+ this.on(i, (data)=>{
+ callback(data)
+ })
+ }
+
+ }
+
+ open() {
+
+ this.socket = new WebSocket(protocol + window.location.host + '/' + uuid)
+
+ this.socket.onclose = this.socket.onerror = ()=>{
+ if (!this.connected()) this.close()
+ }
+
+ this.socket.onopen = (e)=>{
+
+ this.hearbeat = setInterval(()=>{
+ if (!this.connected()) return
+ this.socket.send('["ping"]')
+ this.hearbeatTimeout = setTimeout(()=>{
+ if (this.connected()) this.close()
+ }, hearbeatTimeout)
+ }, hearbeatInterval)
+
+ if (notifications && this.disconnected) notifications.add({
+ icon: 'wifi',
+ message: locales('server_connected'),
+ id: 'ipc_state'
+ })
+
+ this.trigger('connect')
+ this.flush()
+
+ this.socket.onmessage = (e)=>{
+ this.receive(e.data)
+ }
+
+ }
+
+ }
+
+ close() {
+
+ this.socket.onclose = this.socket.onerror = null
+
+ this.socket.close()
+
+ this.socket = null
+
+ clearInterval(this.hearbeat)
+ clearTimeout(this.hearbeatTimeout)
+
+ notifications.add({
+ icon: 'wifi',
+ class: 'error',
+ message: locales('server_disconnected'),
+ id: 'ipc_state',
+ duration: Infinity
+ })
+
+ this.disconnected = true
+
+ clearTimeout(this.reconnect)
+ this.reconnect = setTimeout(()=>{
+ this.open()
+ }, reconnectTimeout)
+
+ }
+
+ connected() {
+
+ return this.socket && this.socket.readyState == this.socket.OPEN
+
+ }
+
+ receive(message) {
+
+ if (typeof message == 'string') {
+
+ var packet = JSON.parse(message)
+
+ if (Array.isArray(packet) && typeof packet[0] == 'string') {
+
+ this.trigger(packet[0], packet[1])
+
+ }
+
+ }
+
+ }
+
+ send(event, data) {
+
+ var packet = JSON.stringify([event, data])
+
+ if (this.connected()) {
+ this.socket.send(packet)
+ } else {
+ this.queue.push(packet)
+ }
+
+ }
+
+ flush(){
+
+ for (var i in this.queue) {
+
+ if (this.connected()) this.socket.send(this.queue[i])
+
+ }
+
+ this.queue = []
+
+ }
+
+}
+
+var ipc = new Ipc()
+
+module.exports = ipc
diff --git a/src/client/locales/en.js b/src/client/locales/en.js
new file mode 100644
index 00000000..787cf07c
--- /dev/null
+++ b/src/client/locales/en.js
@@ -0,0 +1,88 @@
+module.exports = {
+
+ // editor
+ editor: 'Editor',
+ editor_enabled: 'Enabled',
+ editor_grid: 'Grid',
+ editor_tree: 'Project tree',
+ editor_inspector: 'Inspector',
+ editor_percents: 'Relative units (%)',
+
+ // editor context-menu
+ editor_show_in_tree: 'Show in tree',
+ editor_copy: 'Copy',
+ editor_cut: 'Cut',
+ editor_paste: 'Paste',
+ editor_pasteindent: 'ID + 1',
+ editor_clone: 'Clone',
+ editor_addwidget: 'Add widget',
+ editor_addtab: 'Add tab',
+ editor_delete: 'Delete',
+
+ // loadings
+ loading_upload: 'Uploading file...',
+ loading_newclient: 'New client connecting...',
+ loading_server: 'Connecting server...',
+ loading_session: 'Loading session...',
+
+ // file
+ file_open: 'Open',
+ file_open_recent: 'Open recent',
+ file_open_recent_wait: 'List not loaded yet, please close and reopen the menu',
+ file_save: 'Save',
+ file_save_as: 'Save as...',
+ file_import: 'Import',
+ file_export: 'Export',
+
+ // fullscreen
+ fullscreen: 'Fullscreen',
+ fullscreen_unnavailable: 'Fullscreen not available',
+ fullscreen_addtohome: 'You must add this page to your home screen to launch it in fullscreen',
+
+ // inspector
+ inspector_color_confirm: 'Confirm',
+ inspector_color_apply: 'Apply',
+ inspector_error: 'An error just occured, open F12 to read more.',
+
+ // nosleep
+ nosleep: 'Prevent sleep',
+
+ // remote save
+ remotesave_open: 'Open (on the server)',
+ remotesave_save: 'Save (on the server)',
+ remotesave_overwrite: 'This file already exists, do you want to overwrite it ?',
+ remotesave_fail: 'The file could not be saved on the server, use "export" instead',
+ remotesave_success: 'File saved successfully',
+ remotesave_forbidden: 'You\'re note allowed to save on server, use "export instead"',
+
+ // server
+ server_disconnected: 'The connection to the server has been interrupted',
+ server_connected: 'The connection to the server has been restored',
+
+ // session
+ session: 'Session',
+ session_new: 'New session',
+ session_malformed: 'Malformed session file.',
+ session_parsingerror: 'Parsing error.',
+ session_uploaderror: 'Failed to upload session file.',
+ session_unsaved: 'Your changes will be lost if you close this session without saving, continue ?',
+ session_oldversion_title: 'Warning',
+ session_oldversion: 'This session was created with an older version, an automatic conversion has been done.',
+
+ // state
+ state: 'State',
+ state_store: 'Store',
+ state_recall: 'Recall',
+ state_send: 'Send All',
+ state_import: 'Import',
+ state_export: 'Export',
+ state_uploaderror: 'Failed to upload state file.',
+ state_storesuccess: 'State saved',
+ state_recallsuccess: 'State recalled',
+ state_sendsuccess: 'State sent',
+
+ // misc
+ error: 'Error'
+
+
+}
diff --git a/src/client/locales/fr.js b/src/client/locales/fr.js
new file mode 100644
index 00000000..21c706a6
--- /dev/null
+++ b/src/client/locales/fr.js
@@ -0,0 +1,88 @@
+module.exports = {
+
+ // editor
+ editor: 'Editeur',
+ editor_enabled: 'Activé',
+ editor_grid: 'Grille',
+ editor_tree: 'Arborescence',
+ editor_inspector: 'Inspecteur',
+ editor_percents: 'Unités relatives (%)',
+
+ // editor context-menu
+ editor_show_in_tree: 'Voir dans l\'arborescence',
+ editor_copy: 'Copier',
+ editor_cut: 'Couper',
+ editor_paste: 'Coller',
+ editor_pasteindent: 'ID + 1',
+ editor_clone: 'Clone',
+ editor_addwidget: 'Ajouter widget',
+ editor_addtab: 'Ajouter onglet',
+ editor_delete: 'Supprimer',
+
+ // loadings
+ loading_upload: 'Téléversement...',
+ loading_newclient: 'Connexion d\'un nouveau client...',
+ loading_server: 'Connexion au serveur...',
+ loading_session: 'Chargement de la session...',
+
+ // file
+ file_open: 'Ouvrir',
+ file_open_recent: 'Récemment ouvert(s)',
+ file_open_recent_wait: 'Liste non chargée, veuillez fermer puis ouvrir le menu à nouveau',
+ file_save: 'Enregistrer',
+ file_save_as: 'Enregistrer sous...',
+ file_import: 'Importer',
+ file_export: 'Exporter',
+
+ // fullscreen
+ fullscreen: 'Plein écran',
+ fs_unnavailable: 'Plein écran indisponible',
+ fs_addtohome: 'Vous devez ajouter cette page à votre écran d\'accueil pour pouvoir l\'ouvrir en plein écran.',
+
+ // inspector
+ inspector_color_confirm: 'Confirmer',
+ inspector_color_apply: 'Appliquer',
+ inspector_error: 'Une erreur vient de survenir, appuyez sur F12 pour en savoir plus.',
+
+ // nosleep
+ nosleep: 'Empêcher la veille',
+
+ // remote save
+ remotesave_open: 'Ouvrir (sur le serveur)',
+ remotesave_save: 'Enregistrer (sur le serveur)',
+ remotesave_overwrite: 'Un fichier du même nom existe déjà, voulez le remplacer ?',
+ remotesave_fail: 'Le fichier n\'a pas pu être enregistré sur le serveur, utilisez la fonction "exporter"',
+ remotesave_success: 'Le fichier a été enregistré avec succès',
+ remotesave_forbidden: 'Vous n\'êtes pas autorisé à sauvegarder sur le serveur, utilisez la fonction "exporter"',
+
+ // server
+ server_disconnected: 'La connexion avec le serveur a été interrompue',
+ server_connected: 'La connexion avec le serveur a été rétablie',
+
+ // session
+ session: 'Session',
+ session_new: 'Nouvelle session',
+ session_malformed: 'Fichier de session mal formé.',
+ session_parsingerror: 'Erreur à l\'ouverture de la session.',
+ session_uploaderror: 'Échec à l\'envoi du fichier de session.',
+ session_unsaved: 'Vos modifications seront perdues si vous fermez la session actuelle sans sauvegarder, continuer ?',
+ session_oldversion_title: 'Attention',
+ session_oldversion: 'Cette session a été créée avec une ancienne version, une conversion automatique a été appliquée.',
+
+ // state
+ state: 'État',
+ state_store: 'Sauver',
+ state_recall: 'Rappeler',
+ state_send: 'Envoyer',
+ state_import: 'Importer',
+ state_export: 'Exporter',
+ state_uploaderror: 'Échec à l\'envoi du fichier d\'état.',
+ state_storesuccess: 'État de l\'interface sauvegardé',
+ state_recallsuccess: 'État de l\'interface restauré',
+ state_sendsuccess: 'État de de l\'interface envoyé',
+
+ // misc
+ error: 'Erreur'
+
+
+}
diff --git a/src/client/locales/index.js b/src/client/locales/index.js
new file mode 100644
index 00000000..5fccd784
--- /dev/null
+++ b/src/client/locales/index.js
@@ -0,0 +1,9 @@
+var locales = {
+ debug: {/* empty */},
+ en: require('./en'),
+ fr: require('./fr')
+}
+
+var lang = locales[LANG] ? LANG : 'en'
+
+module.exports = key=>locales[lang][key] || `!${key}!`
diff --git a/src/client/managers/cache.js b/src/client/managers/cache.js
new file mode 100644
index 00000000..854f3e17
--- /dev/null
+++ b/src/client/managers/cache.js
@@ -0,0 +1,55 @@
+var keyPrefix = 'osc.'
+
+class Cache {
+
+ set(key, value, persistent = true) {
+
+ var storage = persistent ? localStorage : sessionStorage
+
+ storage.setItem(keyPrefix + key, JSON.stringify(value))
+
+ }
+
+ get(key, persistent = true) {
+
+ var storage = persistent ? localStorage : sessionStorage
+
+ return JSON.parse(storage.getItem(keyPrefix + key))
+
+ }
+
+ remove(key, persistent = true) {
+
+ var storage = persistent ? localStorage : sessionStorage
+
+ storage.removeItem(keyPrefix + key)
+
+ }
+
+ clear(domain) {
+
+ if (domain) {
+
+ for (let storage of [localStorage, sessionStorage]) {
+
+ for (let k in storage) {
+ if (k.indexOf(keyPrefix + domain) === 0) {
+ storage.removeItem(k)
+ }
+ }
+
+ }
+
+
+ } else {
+
+ localStorage.clear()
+ sessionStorage.clear()
+
+ }
+
+ }
+
+}
+
+module.exports = new Cache()
diff --git a/src/client/managers/session/index.js b/src/client/managers/session/index.js
new file mode 100644
index 00000000..dd390315
--- /dev/null
+++ b/src/client/managers/session/index.js
@@ -0,0 +1,196 @@
+var ipc = require('../../ipc/'),
+ parser = require('../../parser'),
+ editor = require('../../editor/'),
+ uiFilebrowser = require('../../ui/ui-filebrowser'),
+ uiFileupload = require('../../ui/ui-fileupload'),
+ UiModal = require('../../ui/ui-modal'),
+ uiLoading = require('../../ui/ui-loading'),
+ {saveAs} = require('file-saver'),
+ widgetManager = require('../widgets'),
+ locales = require('../../locales'),
+ Session = require('./session')
+
+
+var SessionManager = class SessionManager {
+
+ constructor() {
+
+ this.session = null
+ this.lock = false
+ this.lastDir = null
+ this.setSessionPath('')
+
+ ipc.on('connect', ()=>{
+ ipc.send('sessionSetPath', {path: this.sessionPath})
+ })
+
+ }
+
+ load(session, callback) {
+
+ if (this.lock) return
+
+ this.lock = true
+
+ var container = DOM.get('#osc-container')[0]
+
+ uiLoading(locales('loading_session'))
+
+ setTimeout(()=>{
+ try {
+
+ this.session = new Session(session)
+ container.innerHTML = ''
+ parser.reset()
+ parser.parse({
+ data: this.session.getRoot(),
+ parentNode: DOM.get('#osc-container')[0],
+ parent: widgetManager
+ })
+ editor.clearHistory()
+ DOM.get(document, '#osc-greeting-header')[0].classList.add('hidden')
+
+ } catch (err) {
+ uiLoading(false)
+ new UiModal({title: locales('session_parsingerror'), content: err.message, icon: 'exclamation-triangle', closable:true})
+ this.lock = false
+ ipc.send('sessionSetPath', {path: this.sessionPath})
+ throw err
+ }
+
+ for (var h in widgetManager.widgets) {
+ if (widgetManager.widgets[h].value !== undefined) {
+ widgetManager.trigger('change', {
+ widget: widgetManager.widgets[h],
+ id: widgetManager.widgets[h].getProp('id'),
+ linkId: widgetManager.widgets[h].getProp('linkId'),
+ options: {}
+ })
+ }
+ }
+
+ if (editor.enabled) editor.disable()
+
+ DOM.dispatchEvent(window, 'resize')
+
+ setTimeout(()=>{
+ uiLoading(false)
+ this.lock = false
+ editor.unsavedSession = false
+ this.setSessionPath('')
+ if (callback) callback()
+ }, 25)
+
+ }, 25)
+
+ }
+
+ save(path) {
+
+ if (!this.session || READ_ONLY) return
+
+ if (path) this.setSessionPath(path)
+
+ if (!this.sessionPath) return this.saveAs()
+
+ ipc.send('sessionSave', {
+ session: this.session.toJSON(),
+ path: this.sessionPath
+ })
+
+ }
+
+ saveAs() {
+
+ if (!this.session || READ_ONLY) return
+
+ uiFilebrowser({extension: 'json', save:true, directory: this.lastDir}, (path)=>{
+ this.lastDir = path[0]
+ this.save(path)
+ })
+
+ }
+
+ export() {
+
+ var sessionfile = this.session.toJSON(),
+ blob = new Blob([sessionfile],{type : 'application/json'})
+
+ saveAs(blob, new Date().toJSON().slice(0,10)+'_'+new Date().toJSON().slice(11,16) + '.json')
+
+ editor.unsavedSession = false
+
+ }
+
+ open(data) {
+
+ this.load(data.session, ()=>{
+ this.setSessionPath(data.path)
+ ipc.send('sessionOpened', {path: data.path})
+ })
+
+ }
+
+ requestOpen(path) {
+
+ if (editor.unsavedSession && !confirm(locales('session_unsaved'))) return
+ ipc.send('sessionOpen', {path: path})
+
+ }
+
+ browse() {
+
+ if (READ_ONLY) return
+
+ uiFilebrowser({extension: 'json', directory: this.lastDir}, (path)=>{
+ if (editor.unsavedSession && !confirm(locales('session_unsaved'))) return
+ this.lastDir = path[0]
+ ipc.send('sessionOpen',{path:path})
+ })
+
+ }
+
+ import() {
+
+ if (READ_ONLY) return
+
+ uiFileupload('.json', (path, result)=>{
+ var session
+ try {
+ session = JSON.parse(result)
+ } catch (err) {
+ new UiModal({title: locales('session_parsingerror'), content: err.message, icon: 'exclamation-triangle', closable:true})
+ }
+ if (editor.unsavedSession && !confirm(locales('session_unsaved'))) return
+ if (session) sessionManager.load(session, ()=>{
+ ipc.send('sessionSetPath', {path: 'imported'})
+ })
+
+ }, ()=>{
+ new UiModal({title: locales('error'), content: locales('session_uploaderror'), icon: 'exclamation-triangle', closable:true})
+ })
+
+ }
+
+ create() {
+
+ if (editor.unsavedSession && !confirm(locales('session_unsaved'))) return
+
+ this.load(null, ()=>{
+ ipc.send('sessionSetPath', {path: ''})
+ editor.enable()
+ editor.select(widgetManager.getWidgetById('root'))
+ })
+ }
+
+ setSessionPath(path) {
+
+ this.sessionPath = path
+
+ }
+
+}
+
+var sessionManager = new SessionManager()
+
+module.exports = sessionManager
diff --git a/src/client/managers/session/session.js b/src/client/managers/session/session.js
new file mode 100644
index 00000000..2f0b9404
--- /dev/null
+++ b/src/client/managers/session/session.js
@@ -0,0 +1,216 @@
+var semver = require('semver'),
+ UiModal = require('../../ui/ui-modal'),
+ locales = require('../../locales')
+
+module.exports = class Session {
+
+ constructor(data) {
+
+ if (data === null) {
+
+ data = {
+ session: {type: 'root'}
+ }
+
+
+ } else {
+
+ var version = data.version || '0.0.0',
+ warning = false
+
+ for (var converter of converters) {
+
+ if (semver.lte(version, converter.version)) {
+
+ if (converter.global) data = converter.global(data)
+ if (converter.widget) this.applyConvert(data.session, converter.widget)
+
+ if (converter.warning) warning = true
+
+ }
+
+ }
+
+
+ if (warning) {
+
+ new UiModal({title: locales('session_oldversion_title'), content: locales('session_oldversion'), icon: 'exclamation-triangle', closable:true})
+
+
+ }
+
+ }
+
+ data.version = PACKAGE.version
+ data.type = PACKAGE.productName + ' ' + 'session'
+
+ this.data = data
+
+ }
+
+ applyConvert(data, convert) {
+
+ convert(data)
+
+ if (data.widgets) {
+ for (let c of data.widgets) {
+ this.applyConvert(c, convert)
+ }
+ }
+
+ if (data.tabs) {
+ for (let c of data.tabs) {
+ this.applyConvert(c, convert)
+ }
+ }
+
+ }
+
+ getRoot() {
+
+ return this.data.session
+
+ }
+
+ toJSON() {
+
+ return JSON.stringify(this.data, null, ' ')
+
+ }
+
+}
+
+var converters = [
+ {
+ version: '0.49.12',
+ warning: true,
+ global: (data)=>{
+
+ if (Array.isArray(data)) data = data[0]
+
+ return {
+ session: data
+ }
+ },
+ widget: (data)=>{
+
+ data.decimals = data.precision
+
+ if (data.precision === 0) {
+ data.typeTags = 'i'
+ data.decimals = 0
+ }
+ if (data.color !== 'auto') data.colorWidget = data.color
+
+ switch (data.type) {
+
+ case 'toggle':
+ data.type = 'button'
+ data.mode = 'toggle'
+ break
+
+ case 'push':
+ data.type = 'button'
+ data.mode = data.norelease ? 'tap' : 'push'
+ break
+
+ case 'fader':
+ data.design = data.compact ? 'compact' : 'default'
+ break
+
+ case 'meter':
+ data.type = 'fader'
+ data.design = 'compact'
+ data.interaction = false
+ break
+
+
+ case 'tab':
+ case 'panel':
+ case 'root':
+ if (data.widgets && data.widgets.length) {
+ data.innerPadding = false
+ data.padding = 0
+ data.alphaStroke = 0
+ }
+ break
+
+ case 'strip':
+ data.type = 'panel'
+ data.layout = data.horizontal ? 'horizontal' : 'vertical'
+ data.alphaStroke = 0
+ if (data.spacing) {
+ data.padding = data.spacing
+ } else {
+ data.innerPadding = false
+ data.padding = 0
+ }
+ break
+
+ case 'matrix':
+
+
+ data.layout = 'grid'
+ if (Array.isArray(data.matrix) && data.matrix.every(x=>typeof x === 'number')) {
+ data.quantity = data.matrix[0] * data.matrix[1]
+ data.gridTemplate = data.matrix[0]
+ }
+
+
+ var oprops = typeof data.props === 'object' && data.props !== null
+
+ switch (data.widgetType) {
+ case 'toggle':
+ data.widgetType = 'button'
+ if (oprops) data.props.mode = 'toggle'
+ break
+
+ case 'push':
+ data.widgetType = 'button'
+ if (oprops) data.props.mode = data.props.norelease ? 'tap' : 'push'
+ break
+
+ case 'fader':
+ if (oprops) data.props.design = data.props.compact ? 'compact' : 'default'
+ break
+
+ case 'meter':
+ data.widgetType = 'fader'
+ if (oprops) {
+ data.props.design = 'compact'
+ data.props.interaction = false
+ }
+ break
+
+ case 'strip':
+ data.widgetType = 'panel'
+ if (oprops) data.props.layout = data.props.horizontal ? 'horizontal' : 'vertical'
+ break
+ }
+ break
+ case 'eq':
+ data.filter = data.value
+ data.value = ''
+ break
+
+ case 'keys':
+ data.type = 'script'
+ data.event = 'keyboard'
+ data.keyRepeat = data.repeat
+ data.keyBinding = data.binding
+ data.keyType = data.keyDown && data.keyUp ? 'both' : data.keyUp ? 'keyup' : 'keydown'
+ data.script = `
+ // converted from keys widget data
+ if (type === 'keyup') {
+ ${String(data.keyUp).replace(/^JS{{(.*)}}$/, '$1')}
+ } else if (type === 'keydown') {
+ ${String(data.keyDown).replace(/^JS{{(.*)}}$/, '$1')}
+ }
+ `
+ break
+
+ }
+
+ }
+ }
+]
diff --git a/src/client/managers/state.js b/src/client/managers/state.js
new file mode 100644
index 00000000..c8c91cbe
--- /dev/null
+++ b/src/client/managers/state.js
@@ -0,0 +1,254 @@
+var ipc = require('../ipc'),
+ widgetManager = require('./widgets'),
+ cache = require('./cache'),
+ uiFilebrowser = require('../ui/ui-filebrowser'),
+ uiFileupload = require('../ui/ui-fileupload'),
+ notifications = require('../ui/notifications'),
+ {saveAs} = require('file-saver'),
+ locales = require('../locales'),
+ {deepCopy} = require('../utils')
+
+
+var StateManager = class StateManager {
+
+ constructor() {
+
+ this.statePath = ''
+ this.lastDir = null
+
+ this.quickState = cache.get('state.quickState') || null
+
+ this.valueStateQueue = {}
+ this.valueOldPropQueue = {}
+ this.valueNewPropQueue = {}
+ this.queueCounter = 0
+
+ }
+
+ get(filter) {
+
+ var data = {}
+
+ for (let i in widgetManager.widgets) {
+
+ var widget = widgetManager.widgets[i]
+
+ if (filter && !filter(widget)) continue
+
+ if (widget.setValue && widget.getValue) {
+
+ var v = widget.getValue()
+
+ if (v !== undefined) {
+
+ data[widget.getProp('id')] = v
+
+ }
+
+ }
+ }
+
+ return data
+
+ }
+
+ set(preset,send) {
+
+ for (let id in preset) {
+
+ var value = preset[id],
+ widgets = widgetManager.getWidgetById(id)
+
+ if (widgets.length) {
+
+ for (var j = widgets.length - 1; j >= 0; j--) {
+
+ if (widgets[j].setValue) {
+
+ widgets[j].setValue(value, {send:send, sync:true, fromState:true})
+
+ }
+
+ }
+
+ }
+
+ }
+
+ }
+
+ send(options) {
+
+ for (let i in widgetManager.widgets) {
+
+ var widget = widgetManager.widgets[i]
+
+ if (widget.sendValue) {
+ widget.sendValue(null, options)
+ }
+ }
+
+ }
+
+ save(path) {
+
+ if (path) this.statePath = path
+
+ if (!this.statePath) return this.saveAs()
+
+ ipc.send('stateSave', {
+ session: JSON.stringify(this.get(), null, ' '),
+ path: this.statePath
+ })
+
+ }
+
+ saveAs() {
+
+ uiFilebrowser({extension: 'state', save:true, directory: this.lastDir}, (path)=>{
+ this.lastDir = path[0]
+ this.save(path)
+ })
+
+ }
+
+ browse() {
+
+ uiFilebrowser({extension: 'state', directory: this.lastDir}, (path)=>{
+ this.lastDir = path[0]
+ ipc.send('stateOpen',{path: path})
+ })
+
+ }
+
+ load(state, send, path) {
+
+ if (!state) return
+
+ this.setStatePath(path)
+
+ try {
+ if (typeof state === 'string') {
+ state = JSON.parse(state)
+ }
+
+ if (Array.isArray(state)) {
+ // backward compatibility
+ var ostate = {}
+ for (var i in state) {
+ ostate[state[i][0]] = state[i][1]
+ }
+ state = ostate
+ }
+
+ this.set(state, send)
+ notifications.add({
+ icon: 'sliders-h',
+ message: locales('state_recallsuccess')
+ })
+ } catch(e) {
+ this.loadError()
+ }
+
+ }
+
+ loadError(){
+
+ notifications.add({
+ class: 'error',
+ message: locales('state_uploaderror')
+ })
+
+ }
+
+
+ import() {
+
+ uiFileupload('.state', (path, result)=>{
+ this.load(result, true)
+ }, (e)=>{
+ this.loadError()
+ })
+
+ }
+
+ export() {
+
+ var state = JSON.stringify(this.get(),null,' ')
+ var blob = new Blob([state],{type : 'application/json'})
+ saveAs(blob, new Date().toJSON().slice(0,10)+'_'+new Date().toJSON().slice(11,16) + '.state')
+
+ }
+
+ quickSave() {
+
+ this.quickState = deepCopy(this.get())
+ localStorage.setItem('osc.state.quickState', JSON.stringify(this.quickState))
+
+ }
+
+ quickLoad() {
+
+ this.load(this.quickState, true)
+
+ }
+
+ setStatePath(path) {
+
+ if (!path) return
+ this.statePath = path
+
+ }
+
+ pushValueState(id, value) {
+ this.valueStateQueue[id] = value
+ }
+
+ pushValueOldProp(id, value) {
+ this.valueOldPropQueue[id] = typeof value == 'object' ? JSON.stringify(value) : value
+ }
+
+ pushValueNewProp(id, value) {
+ this.valueNewPropQueue[id] = typeof value == 'object' ? JSON.stringify(value) : value
+ if (this.queueCounter == 0) this.flush()
+ }
+
+ flush(){
+
+ for (let id in this.valueStateQueue) {
+ if (this.valueStateQueue[id] !== undefined) {
+ for (let w of widgetManager.getWidgetById(id)) {
+ w.setValue(this.valueStateQueue[id], {sync: true, fromState:true, fromEdit: true})
+ }
+ }
+ }
+
+ for (let id in this.valueNewPropQueue) {
+ if (this.valueNewPropQueue[id] != this.valueOldPropQueue[id]) {
+ for (let w of widgetManager.getWidgetById(id)) {
+ w.setValue(w.getProp('value'), {sync: true, fromState:true})
+ }
+ }
+ }
+
+ this.valueStateQueue = {}
+ this.valueOldPropQueue = {}
+ this.valueNewPropQueue = {}
+ }
+
+ incrementQueue() {
+ this.queueCounter++
+ }
+
+ decrementQueue() {
+ this.queueCounter--
+ if (this.queueCounter == 0) {
+ this.flush()
+ }
+ }
+
+}
+
+var stateManager = new StateManager()
+
+module.exports = stateManager
diff --git a/src/client/managers/widgets.js b/src/client/managers/widgets.js
new file mode 100644
index 00000000..940b8f92
--- /dev/null
+++ b/src/client/managers/widgets.js
@@ -0,0 +1,340 @@
+var EventEmitter = require('../events/event-emitter'),
+ ipc = require('../ipc/')
+
+class WidgetManager extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.widgets = {}
+ this.children = []
+
+ this.addressRoute = {}
+ this.idRoute = {}
+ this.linkIdRoute = {}
+
+ this.linkIdLock = []
+ this.linkIdLockDepth = 0
+
+ this.scrollingWidgets = []
+
+ this.preArgsSeparator = '||||'
+
+ this.on('change', this.onChange.bind(this))
+
+ ipc.on('connect', ()=>{
+ for (var hash in this.widgets) {
+ this.registerWidget(this.widgets[hash])
+ }
+ })
+ setInterval(()=>{
+
+ this.trigger('root-nav-changed')
+ }, 1000)
+
+ }
+
+ onChange(e) {
+
+ var {id, widget, linkId, options} = e
+
+ if (linkId) {
+ if (!Array.isArray(linkId)) linkId = [linkId]
+ linkId = linkId.map(x=>String(x).replace(/^>>\s*/, '')).filter(x=>x.indexOf('<<') < 0)
+ linkId = linkId.filter(x=>this.linkIdLock.indexOf(x)<0)
+ this.linkIdLock = this.linkIdLock.concat(linkId)
+ this.linkIdLockDepth++
+ }
+
+ var widgetsById = this.getWidgetById(id),
+ widgetsByLinkId = linkId ? this.getWidgetByLinkId(linkId) : []
+
+ // Widget that share the same id will update each other
+ // without sending any extra osc message
+ if (widgetsById.length > 1) {
+ let v = widget.getValue()
+ for (let i in widgetsById) {
+ if (widgetsById[i] !== widget) {
+ widgetsById[i].setValue(v,{send:false,sync:false, id})
+ }
+ }
+ }
+
+ // widgets that share the same linkId will update each other.
+ // Updated widgets will send osc messages normally
+ if (widgetsByLinkId.length > 0) {
+ let v = widget.getValue()
+ for (let i in widgetsByLinkId) {
+ if (widgetsByLinkId[i] !== widget) {
+ widgetsByLinkId[i].setValue(v,{send: options.send,sync: true, id})
+ }
+ }
+ }
+
+ if (linkId && this.linkIdLockDepth) {
+ this.linkIdLockDepth--
+ if (!this.linkIdLockDepth) {
+ this.linkIdLock = []
+ }
+ }
+
+ }
+
+ createAddressRef(widget, preArgs, address) {
+
+ preArgs = widget ? widget.getProp('preArgs') : preArgs
+ address = widget ? widget.getProp('address') === 'auto' ? '/' + widget.getProp('id') : widget.getProp('address') : address
+
+ if (!Array.isArray(preArgs) && preArgs !== '') preArgs = [preArgs]
+ if (preArgs === '') preArgs = []
+
+ preArgs = preArgs.map(x=>typeof x === 'object' && x !== null && x.value !== undefined ? x.value : x)
+
+ return preArgs && preArgs.length ?
+ address + this.preArgsSeparator + preArgs.join(this.preArgsSeparator)
+ : address
+
+ }
+
+ addWidget(widget) {
+
+ var hash = widget.hash,
+ address = this.createAddressRef(widget),
+ id = widget.getProp('id'),
+ linkId = widget.getProp('linkId'),
+ scroll = widget.getProp('scroll')
+
+
+ this.widgets[hash] = widget
+
+ if (!this.idRoute[id]) this.idRoute[id] = []
+ this.idRoute[id].push(hash)
+
+ if (address) {
+ if (!this.addressRoute[address]) this.addressRoute[address] = []
+ this.addressRoute[address].push(hash)
+ }
+
+ if (linkId) {
+ if (!Array.isArray(linkId)) linkId = [linkId]
+ linkId = linkId.map(x=>String(x).replace(/^<<\s*/, '')).filter(x=>x.indexOf('>>') < 0)
+ for (var i in linkId) {
+ if (linkId[i]) {
+ if (!this.linkIdRoute[linkId[i]]) this.linkIdRoute[linkId[i]] = []
+ this.linkIdRoute[linkId[i]].push(hash)
+ }
+ }
+ }
+
+ if (scroll) {
+ this.scrollingWidgets.push(hash)
+ }
+
+ this.registerWidget(widget)
+
+ }
+
+ registerWidget(widget, updatedData, oldData) {
+
+ ipc.send('addWidget', {
+ hash: widget.hash,
+ data: updatedData || {
+ preArgs: widget.getProp('preArgs'),
+ target: widget.getProp('target'),
+ typeTags: widget.getProp('typeTags'),
+ address: widget.getProp('address') === 'auto' ? '/' + widget.getProp('id') : widget.getProp('address'),
+ }
+ })
+
+ if (updatedData && oldData) {
+ var address = this.createAddressRef(null, oldData.preArgs, oldData.address),
+ newAddress = this.createAddressRef(widget),
+ hash = widget.hash
+
+ if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
+
+ if (!this.addressRoute[newAddress]) this.addressRoute[newAddress] = []
+ this.addressRoute[newAddress].push(hash)
+ }
+
+ }
+
+ removeWidget(widget) {
+
+ var hash = widget.hash,
+ address = this.createAddressRef(widget),
+ linkId = widget.getProp('linkId'),
+ id = widget.getProp('id'),
+ scroll = widget.getProp('scroll')
+
+ if (this.widgets[hash]) {
+ if (this.widgets[hash].onRemove) this.widgets[hash].onRemove()
+
+ delete this.widgets[hash]
+
+ ipc.send('removeWidget', {
+ hash:hash
+ })
+
+ widget.trigger('widget-removed', {widget: widget})
+
+ }
+ if (id && this.idRoute[id].indexOf(hash) != -1) this.idRoute[id].splice(this.idRoute[id].indexOf(hash), 1)
+ if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
+ if (scroll && this.scrollingWidgets.indexOf(hash) != -1) this.scrollingWidgets.splice(this.scrollingWidgets.indexOf(hash), 1)
+
+ if (!Array.isArray(linkId)) linkId = [linkId]
+ linkId = linkId.map(x=>String(x))
+ for (var i in linkId) {
+ if (linkId[i] && this.linkIdRoute[linkId[i]] && this.linkIdRoute[linkId[i]].indexOf(hash) != -1) this.linkIdRoute[linkId[i]].splice(this.linkIdRoute[linkId[i]].indexOf(hash), 1)
+ }
+
+ }
+
+ removeWidgets(widgets, nested) {
+
+ for (let i in widgets) {
+
+ if (Array.isArray(widgets[i])) {
+
+ this.removeWidgets(widgets[i], true)
+
+ } else if (this.widgets[widgets[i].hash]) {
+
+ this.removeWidget(widgets[i])
+
+ }
+
+ }
+
+ if (!nested) this.purge()
+
+ }
+
+ purge() {
+
+ for (let route of [this.addressRoute, this.idRoute, this.linkIdRoute]) {
+ for (let key in route) {
+ for (let i=route[key].length-1; i>=0; i--) {
+ let hash = route[key][i]
+ if (!this.widgets[hash]) {
+ route[key].splice(i, 1)
+ }
+ }
+ }
+ }
+
+ for (let i in this.scrollingWidgets) {
+ if (!this.widgets[this.scrollingWidgets[i]]) {
+ this.scrollingWidgets.splice(i, 1)
+ }
+ }
+
+ }
+
+ reset() {
+
+ this.removeWidgets(Object.values(this.widgets))
+
+ this.off()
+
+ this.on('change', this.onChange.bind(this))
+
+ }
+
+
+ getWidgetBy(key, dict, widgets = []) {
+
+ var hash, w
+
+ if (Array.isArray(key)) {
+ for (let i in key) {
+ this.getWidgetBy(key[i], dict, widgets)
+ }
+ return widgets
+ }
+
+ if (dict[key]) {
+ for (let i = dict[key].length-1; i>=0; i--) {
+ hash = dict[key][i]
+ w = this.widgets[hash]
+ if (!w) {
+ dict[key].splice(i,1)
+ } else if (widgets.indexOf(w) == -1) {
+ widgets.push(w)
+ }
+ }
+ }
+
+ return widgets
+
+ }
+
+ getWidgetById(id) {
+
+ return this.getWidgetBy(id, this.idRoute)
+
+ }
+
+ getWidgetByLinkId(linkId) {
+
+ return this.getWidgetBy(linkId, this.linkIdRoute)
+
+ }
+
+ getWidgetByAddress(address) {
+
+ return this.getWidgetBy(address, this.addressRoute)
+
+ }
+
+ getWidgetByAddressAndArgs(address, args) {
+
+ var addressref = address,
+ restArgs = args
+
+ if (typeof args == 'object' && args != null) {
+ for (var i = args.length; i >= 0; i--) {
+
+ var ref = this.createAddressRef(null, args.slice(0,i), address)
+
+ if (this.getWidgetByAddress(ref).length) {
+ addressref = ref
+ restArgs = args.slice(i, args.length)
+ break
+ }
+
+ }
+ } else {
+ restArgs = args
+ }
+
+
+ if (restArgs == null || restArgs.length == 0) restArgs = null
+ else if (restArgs.length == 1) restArgs = restArgs[0]
+
+
+ var widgets = this.getWidgetByAddress(addressref)
+
+ return [
+ widgets,
+ restArgs
+ ]
+
+ }
+
+ getWidgetByElement(e, filter = '') {
+ var element = e ? e.closest('[data-widget]' + filter) : undefined
+ if (element) {
+ return element._widget_instance ?
+ element._widget_instance :
+ this.widgets[element.getAttribute('data-widget')]
+ }
+ }
+
+}
+
+var widgetManager = new WidgetManager()
+
+module.exports = widgetManager
diff --git a/src/client/osc.js b/src/client/osc.js
new file mode 100644
index 00000000..947f6b0e
--- /dev/null
+++ b/src/client/osc.js
@@ -0,0 +1,82 @@
+var widgetManager = require('./managers/widgets'),
+ EventEmitter = require('./events/event-emitter'),
+ ipc = require('./ipc/'),
+ {deepEqual} = require('./utils')
+
+var Osc = class Osc extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.syncOnly = false
+ this.remoteControl = {}
+ this.serverTargets = []
+
+ setTimeout(()=>{
+ osc.remoteControl = require('./remote-control')
+ })
+
+ }
+
+ send(data) {
+
+ if (this.syncOnly) {
+
+ this.sync(data)
+
+ } else {
+
+ ipc.send('sendOsc', data)
+
+ }
+
+ }
+
+ sync(data) {
+
+ ipc.send('syncOsc', data)
+
+ }
+
+ receive(data){
+
+ if (typeof this.remoteControl.exists === 'function' && this.remoteControl.exists(data.address)) this.remoteControl.exec(data.address, data.args)
+
+ var [widgets, restArgs] = widgetManager.getWidgetByAddressAndArgs(data.address, data.args)
+
+ for (let i in widgets) {
+
+ let widgetTarget = widgets[i].getProp('target'),
+ match = true
+
+ if (data._rawTarget) {
+ // if the message target is provided (when message comes from another client connected to the same server)
+ // then we only update the widgets that have the exact same target
+ match = deepEqual(widgetTarget, data._rawTarget)
+ } else if (data.host === 'midi') {
+ // if the message comes from a midi port, only update widgets that send to that port
+ let widgetArrayTarget = Array.isArray(widgetTarget) ? widgetTarget : [widgetTarget],
+ strTarget = data.host + ':' + data.port
+
+ match = widgetArrayTarget.includes(strTarget) ||
+ (!widgetArrayTarget.includes(null) && this.serverTargets.includes(strTarget))
+
+ }
+
+ if (match) {
+ widgets[i].setValue(restArgs,{send:false,sync:true,fromExternal:!data.target})
+ }
+
+ }
+
+ this.trigger(data.address, data.args)
+
+ }
+
+}
+
+
+var osc = new Osc()
+
+module.exports = osc
diff --git a/src/client/parser.js b/src/client/parser.js
new file mode 100644
index 00000000..28702e57
--- /dev/null
+++ b/src/client/parser.js
@@ -0,0 +1,122 @@
+var widgetManager = require('./managers/widgets'),
+ stateManager = require('./managers/state'),
+ {deepCopy} = require('./utils')
+
+var Parser = class Parser {
+
+ constructor() {
+
+ this.iterators = {}
+ this.widgets = {}
+ this.defaults = {}
+
+ }
+
+ getIterator(id) {
+
+ this.iterators[id] = (this.iterators[id] || 0) + 1
+ return this.iterators[id]
+
+ }
+
+ reset() {
+
+ this.iterators = {}
+ widgetManager.reset()
+
+ }
+
+ parse(options) {
+
+ var {
+ data,
+ parentNode,
+ parent,
+ tab,
+ reCreateOptions,
+ children,
+ index,
+ hash,
+ locals
+ } = options
+
+ var props = data
+
+ // Set default widget type
+ props.type = tab ? 'tab' : props.type || 'fader'
+
+ if (!this.widgets[props.type]) {
+ console.error('[' + props.id + '] Widget type "' + props.type +'" does not exist, falling back to "fader"')
+ props.type = 'fader'
+ }
+
+ // Get widget's defaults
+ var defaults = this.defaults[props.type]
+
+ // Set widget's undefined options to default
+ for (let i in defaults) {
+ if (i.indexOf('_') !== 0 && props[i] === undefined) props[i] = deepCopy(defaults[i])
+ }
+
+ // Genrate widget's id, based on its type
+ if (props.id === 'auto' || !props.id) {
+ var id
+ while (!id || widgetManager.getWidgetById(id).length) {
+ id = props.type + '_' + this.getIterator(props.type)
+ }
+ props.id = id
+ }
+
+ // Remove props that don't apply
+ for (let j in props) {
+ if (defaults[j] === undefined || j[0] === '_') delete props[j]
+ }
+
+ // create widget
+ var widget = new this.widgets[props.type]({
+ props,
+ parent,
+ parentNode,
+ reCreateOptions,
+ children,
+ hash,
+ locals,
+ })
+
+ widgetManager.addWidget(widget)
+
+ widget.created(index)
+
+ // set widget's initial state
+ var defaultValue = widget.getProp('default'),
+ currentValue = widget.getProp('value')
+
+ if (currentValue !== '' && currentValue !== undefined) {
+
+ stateManager.pushValueNewProp(widget.getProp('id'), currentValue)
+
+ } else if (defaultValue !== '' && defaultValue !== undefined) {
+
+ widget.setValue(defaultValue)
+
+ }
+
+
+ parentNode.appendChild(widget.container)
+ widget.mounted = true
+
+ // Editor needs to get the container object
+ return widget
+
+ }
+
+}
+
+var parser = new Parser()
+
+module.exports = parser
+
+parser.widgets = require('./widgets/').widgets
+for (var k in parser.widgets) {
+ parser.defaults[k] = parser.widgets[k].defaults()._props()
+}
diff --git a/src/client/remote-control.js b/src/client/remote-control.js
new file mode 100644
index 00000000..560a5864
--- /dev/null
+++ b/src/client/remote-control.js
@@ -0,0 +1,246 @@
+var {updateWidget} = require('./editor/data-workers'),
+ editor = require('./editor'),
+ widgetManager = require('./managers/widgets'),
+ stateManager = require('./managers/state'),
+ deepExtend = require('deep-extend'),
+ notifications = require('./ui/notifications')
+
+var callbacks = {
+ '/EDIT': function(args) {
+
+ if (READ_ONLY) return
+
+ var [id, json, opts] = args,
+ newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
+ options = typeof opts == 'string' ? JSON.parseFlex(opts) : {},
+ widgets = widgetManager.getWidgetById(id)
+
+ if (!widgets.length) return
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ var widget = widgets[i],
+ data = widget.props
+
+ for (var k in newdata) {
+ data[k] = newdata[k]
+ }
+
+ updateWidget(widget, {
+ reuseChildren: !(newdata.widgets || newdata.tabs),
+ changedProps: Object.keys(newdata)
+ })
+
+ }
+
+ editor.pushHistory()
+
+ if (options.noWarning) editor.unsavedSession = false
+
+ },
+ '/EDIT/MERGE': function(args) {
+
+ if (READ_ONLY) return
+
+ var [id, json, opts] = args,
+ newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
+ options = typeof opts == 'string' ? JSON.parseFlex(opts) : {},
+ widgets = widgetManager.getWidgetById(id)
+
+ if (!widgets.length) return
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ var widget = widgets[i],
+ data = widget.props
+
+ deepExtend(data, newdata)
+
+ updateWidget(widget, {
+ reuseChildren: !(newdata.widgets || newdata.tabs),
+ changedProps: Object.keys(newdata)
+ })
+
+ }
+
+ editor.pushHistory()
+
+ if (options.noWarning) editor.unsavedSession = false
+
+ },
+ '/EDIT/UNDO': function(args) {
+
+ if (READ_ONLY) return
+
+ editor.undo()
+
+ },
+ '/EDIT/REDO': function(args) {
+
+ if (READ_ONLY) return
+
+ editor.redo()
+
+ },
+ '/EDIT/GET': function(args) {
+
+ var [target, idOrAddress, ...preArgs] = args,
+ widgets = []
+
+ if (idOrAddress[0] == '/') {
+
+ widgets = widgetManager.getWidgetByAddress(
+ widgetManager.createAddressRef(null, preArgs, idOrAddress)
+ )
+
+ } else {
+
+ widgets = widgetManager.getWidgetById(idOrAddress)
+
+ }
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ return widgets[i].sendValue({
+ target: [target],
+ address: '/EDIT/GET',
+ preArgs: [idOrAddress, ...preArgs],
+ v: JSON.stringify(widgets[i].props),
+ noSync: true
+ }, {force: true})
+
+ }
+
+ },
+ '/GET': function(args, transparentReply) {
+
+ var [target, idOrAddress, ...preArgs] = args,
+ widgets = []
+
+ if (idOrAddress[0] == '/') {
+
+ widgets = widgetManager.getWidgetByAddress(
+ widgetManager.createAddressRef(null, preArgs, idOrAddress)
+ )
+
+ } else {
+
+ widgets = widgetManager.getWidgetById(idOrAddress)
+
+ }
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ let overrides = {
+ target: [target],
+ noSync: true
+ }
+
+ if (!transparentReply) {
+
+ overrides.address = '/GET'
+ overrides.preArgs = [idOrAddress, ...preArgs]
+
+ }
+
+ return widgets[i].sendValue(overrides, {force: true})
+
+ }
+
+ },
+ '/GET/#': function(args) {
+
+ callbacks['/GET'](args, true)
+
+ },
+ '/SET': function(args) {
+
+ var [idOrAddress, ...preArgsOrValue] = args,
+ widgets = [],
+ value = null
+
+ if (idOrAddress[0] == '/') {
+
+ [widgets, value] = widgetManager.getWidgetByAddressAndArgs(
+ idOrAddress,
+ preArgsOrValue
+ )
+
+ } else {
+
+ widgets = widgetManager.getWidgetById(idOrAddress)
+ value = preArgsOrValue
+ if (value.length == 0) value = null
+ else if (value.length == 1) value = value[0]
+
+ }
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ return widgets[i].setValue(value, {
+ sync: true,
+ send: true
+ })
+
+ }
+
+ },
+ '/STATE/GET': function(args) {
+
+ if (Array.isArray(args)) args = args[0]
+
+ var target = args,
+ root = widgetManager.getWidgetById('root')[0],
+ state = stateManager.get()
+
+ root.sendValue({
+ target: [target],
+ address: '/STATE/GET',
+ preArgs: [],
+ v: JSON.stringify(state),
+ noSync: true
+ }, {force: true})
+
+ },
+ '/STATE/SET': function(args) {
+
+ if (Array.isArray(args)) args = args[0]
+
+ var json = args,
+ data = typeof json == 'string' ? JSON.parseFlex(json) : json
+
+ stateManager.set(data)
+
+ },
+ '/STATE/STORE': function(args) {
+
+ stateManager.quickSave()
+
+ },
+ '/STATE/RECALL': function(args) {
+
+ stateManager.quickLoad()
+
+ },
+ '/NOTIFY': function(args) {
+
+ if (!Array.isArray(args)) args = [args]
+
+ notifications.add({
+ message: args.join('\n') || ' '
+ })
+
+ },
+
+}
+
+module.exports = {
+ exec: function(name, args){
+ if (callbacks[name]) {
+ callbacks[name](args)
+ }
+ },
+ exists: function(name){
+ return name in callbacks
+ }
+}
diff --git a/src/client/stacktrace.js b/src/client/stacktrace.js
new file mode 100644
index 00000000..86067d7d
--- /dev/null
+++ b/src/client/stacktrace.js
@@ -0,0 +1,28 @@
+var StackTrace = require('stacktrace-js'),
+ ipc = require('./ipc')
+
+window.onerror = function(msg,url,row,col, error) {
+
+ StackTrace.fromError(error).then((stackframes)=>{
+
+ var stringifiedStack = stackframes.filter((sf)=>{
+
+ return !sf.fileName.match('browser-pack')
+
+ }).map(function(sf) {
+
+ if (sf.functionName.match(/Object\./)) sf.functionName = 'require'
+
+ return ` at ${sf.functionName} (${sf.fileName}:${sf.lineNumber}:${sf.columnNumber})`
+
+ }).join('\n')
+
+ ipc.send('errorLog', `(ERROR, CLIENT) ${msg}\n${stringifiedStack}`)
+
+ }).catch(()=>{
+
+ ipc.send('errorLog', `(ERROR, CLIENT) ${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
+
+ })
+
+}
diff --git a/src/client/ui/context-menu.js b/src/client/ui/context-menu.js
new file mode 100644
index 00000000..13b4dd78
--- /dev/null
+++ b/src/client/ui/context-menu.js
@@ -0,0 +1,207 @@
+var html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
+ UiWidget = require('./ui-widget'),
+ mod = (navigator.platform || '').match('Mac') ? 'cmd' : 'ctrl',
+ MENU_CONTAINER
+
+
+class ContextMenu extends UiWidget {
+
+ constructor(options={}){
+
+ super(options)
+
+ if (!MENU_CONTAINER) MENU_CONTAINER = DOM.get('osc-workspace')[0]
+
+
+ this.container = html``
+ this.clickHandler = (e)=>{
+ if (this.container && !this.container.contains(e.target)) {
+ this.close()
+ }
+ }
+
+
+ this.position = options.position
+ if (this.position) {
+ this.container.style.top = this.position[0] + 'rem'
+ this.container.style.left = this.position[1] + 'rem'
+ }
+
+ this.container.addEventListener('click', (e)=>{
+ e.preventDefault()
+ if (e.target._action){
+ e.target._action()
+ this.close()
+ }
+ })
+
+ this.hoverNode = null
+ this.container.addEventListener('mousemove', (e)=>{
+ if (this.hoverNode === e.target) return
+ this.hoverNode = e.target
+ if (!e.target.classList.contains('focus')) {
+ DOM.each(e.target.parentNode, '.focus', (el)=>{
+ el.classList.remove('focus')
+ })
+ e.target.classList.add('focus')
+ }
+ })
+
+ this.container.addEventListener('touchstart', (e)=>{
+ if (!e.target.classList.contains('focus')) {
+ DOM.each(e.target.parentNode, '.focus', (el)=>{
+ el.classList.remove('focus')
+ })
+ e.target.classList.add('focus')
+ } else {
+ e.target.classList.remove('focus')
+ DOM.each(e.target, '.focus', (el)=>{
+ el.classList.remove('focus')
+ })
+ }
+ })
+
+
+ }
+
+ parse(actions, node) {
+
+ for (let action of actions) {
+
+ if (action.separator) {
+
+ node.appendChild(html`
`)
+
+ } else if (Array.isArray(action.action)) {
+
+ let submenu = html``,
+ label = typeof action.label === 'function' ? action.label() : action.label,
+ iclass = typeof action.class === 'function' ? action .class() : action.class,
+ item = html`${raw(label)}
`
+
+ item.appendChild(submenu)
+ node.appendChild(item)
+
+ this.parse(action.action, submenu)
+
+
+ } else {
+
+ let label = typeof action.label === 'function' ? action.label() : action.label,
+ iclass = typeof action.class === 'function' ? action.class() : action.class,
+ item = html`${raw(label)}
`
+
+ item._action = action.action
+ node.appendChild(item)
+
+ if (action.shortcut) {
+
+ item.appendChild(html`${action.shortcut.replace('mod', mod)}
`)
+
+ }
+
+ }
+
+ }
+
+ }
+
+ open(e, actions, parent) {
+
+ this.container.innerHTML = ''
+ this.parse(actions, this.container)
+
+ MENU_CONTAINER.appendChild(this.container)
+
+ if (!this.position) {
+ this.container.style.top = e.pageY / PXSCALE + 'rem'
+ this.container.style.left = e.pageX / PXSCALE + 'rem'
+ }
+
+
+ this.correctPosition(this.container)
+
+ DOM.each(this.container, '.context-menu', (m)=>{
+ this.correctPosition(m, m.parentNode)
+ })
+
+ document.addEventListener('fast-click', this.clickHandler, true)
+ document.addEventListener('fast-right-click', this.clickHandler, true)
+
+ this.trigger('open')
+
+ }
+
+ close() {
+
+ if (this.container) {
+
+ this.container.parentNode.removeChild(this.container)
+
+ // remove position fix
+ this.container.style.bottom = ''
+ this.container.style.right = ''
+ this.container.style.marginRight = ''
+
+ }
+
+ document.removeEventListener('fast-click', this.clickHandler, true)
+ document.removeEventListener('fast-right-click', this.clickHandler, true)
+
+ this.hoverNode = null
+
+ this.trigger('close')
+
+ }
+
+ correctPosition(menu, parent) {
+
+ var position = DOM.offset(menu),
+ width = menu.offsetWidth,
+ height = menu.offsetHeight,
+ totalWidth = MENU_CONTAINER.offsetWidth,
+ totalHeight = MENU_CONTAINER.offsetHeight
+
+ if (width + position.left > totalWidth) {
+ if (position.left - width > 0) {
+ menu.style.right = parent ? '100%' : '0'
+ menu.style.left = 'auto'
+ menu.style.marginRight = '-0.5rem'
+ } else {
+ menu.style.left = (parent.offsetWidth + (totalWidth - width - position.left)) / PXSCALE + 'rem'
+ }
+ }
+
+ if (height + position.top > totalHeight && position.top - height > 0) {
+ menu.style.top = 'auto'
+ menu.style.bottom = '0rem'
+ }
+
+ }
+
+ bindShortcuts(actions) {
+
+ for (let action of actions) {
+
+ if (Array.isArray(action.action)) {
+
+ this.bindShortcuts(action.action)
+
+ } else if (action.shortcut && action.action) {
+
+ keyboardJS.bind(action.shortcut, (e)=>{
+ e.preventDefault()
+ action.action()
+ })
+
+ }
+
+ }
+
+ }
+
+}
+
+module.exports = ContextMenu
diff --git a/src/client/ui/fullscreen.js b/src/client/ui/fullscreen.js
new file mode 100644
index 00000000..b3eebf33
--- /dev/null
+++ b/src/client/ui/fullscreen.js
@@ -0,0 +1,41 @@
+var screenfull = require('screenfull'),
+ UiModal = require('./ui-modal'),
+ locales = require('../locales')
+
+var fullscreen
+
+if (screenfull.isEnabled) {
+
+ fullscreen = screenfull
+
+} else {
+
+ class IOSFullScreen {
+
+ constructor(){
+
+ this.enabled = !navigator.standalone
+ this.isFullScreen = navigator.standalone
+
+ }
+
+ toggle(){
+
+ new UiModal({
+ title: locales('fullscreen_unnavailable'),
+ content: locales('fullscreen_addtohome'),
+ closable: true
+ })
+
+ }
+
+ on(){}
+
+ }
+
+ fullscreen = new IOSFullScreen()
+
+}
+
+
+module.exports = fullscreen
diff --git a/src/client/ui/index.js b/src/client/ui/index.js
new file mode 100644
index 00000000..16f94311
--- /dev/null
+++ b/src/client/ui/index.js
@@ -0,0 +1,8 @@
+var UiSidePanel = require('./ui-sidepanel'),
+ locales = require('../locales')
+
+
+module.exports = {
+ leftUiSidePanel: new UiSidePanel({selector: 'osc-panel-container.left', label: locales('editor_tree')}),
+ rightUiSidePanel: new UiSidePanel({selector: 'osc-panel-container.right', label: locales('editor_inspector')})
+}
diff --git a/src/client/ui/init.js b/src/client/ui/init.js
new file mode 100644
index 00000000..f88ad20a
--- /dev/null
+++ b/src/client/ui/init.js
@@ -0,0 +1,6 @@
+require('./zoom')
+require('../events/click')
+require('./ios')
+require('./notifications')
+require('./ui-workspace')
+require('./ui-toolbar')
diff --git a/src/client/ui/ios.js b/src/client/ui/ios.js
new file mode 100644
index 00000000..64372b29
--- /dev/null
+++ b/src/client/ui/ios.js
@@ -0,0 +1,42 @@
+// Prevent iOS Pull-To-Refresh
+
+var iOS13 = (
+ navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 // iPad
+ || navigator.userAgent.match(/iPhone OS (1[3-9])/) // iPhone
+ ),
+ iOS = navigator.platform.match(/iPhone|iPod|iPad/) || iOS13
+
+if (iOS && !iOS13) {
+
+ // prevent overscroll
+ // breaks scrolling on iOS13 (besides it doesn't seem to be needed)
+
+ var supportsPassiveOption = false
+ try {
+ document.createElement('div').addEventListener('test', function() {}, {
+ get passive() {
+ supportsPassiveOption = true
+ return false
+ }
+ })
+ } catch(e) {}
+
+ iOS = true
+
+ var preventNextMove = false
+
+ document.addEventListener('touchstart', (e)=>{
+ if (e.touches.length === 1 && !e.target._drag_widget) preventNextMove = true
+ }, supportsPassiveOption ? {passive: false} : false)
+
+ document.addEventListener('touchmove', (e)=>{
+ // preventDefault the first overscrolling touchmove
+ if (preventNextMove) {
+ preventNextMove = false
+ e.preventDefault()
+ }
+ }, supportsPassiveOption ? {passive: false} : false)
+
+}
+
+module.exports = iOS
diff --git a/src/client/ui/notifications.js b/src/client/ui/notifications.js
new file mode 100644
index 00000000..2a5f329a
--- /dev/null
+++ b/src/client/ui/notifications.js
@@ -0,0 +1,121 @@
+var html = require('nanohtml'),
+ morph = require('nanomorph')
+
+
+var DEFAULT_DURATION = 3500
+
+class Toast {
+
+ constructor(data) {
+
+ this.id = data.id || Date.now()
+ this.update(data)
+
+ }
+
+ update(data) {
+
+ this.expires = Date.now() + (data.duration || DEFAULT_DURATION)
+
+ var toast = html`
+
+ `
+
+ DOM.get(toast, '.content')[0].textContent = data.message
+
+ if (this.html) {
+ this.html = morph(this.html, toast)
+ this.html.style.height = this.html.offsetHeight + 'px'
+ } else {
+ this.html = toast
+ }
+
+ }
+
+ appendTo(el) {
+
+ el.appendChild(this.html)
+ this.html.style.height = this.html.offsetHeight + 'px'
+
+ }
+
+ removeFrom(el) {
+
+ this.html.classList.add('remove')
+ setTimeout(()=>{
+ if (el.contains(this.html)) el.removeChild(this.html)
+ }, 200)
+
+ }
+
+}
+
+class Notifications {
+
+ constructor() {
+
+ this.container = DOM.get('#notifications')[0]
+ this.toasts = []
+
+ this.loop = null
+
+ }
+
+ add(data) {
+
+ if (data.id) {
+ var match = this.toasts.filter(x => x.id === data.id)
+ if (match.length) {
+ return match[0].update(data)
+ }
+ }
+
+ var toast = new Toast(data)
+
+ toast.appendTo(this.container)
+ this.toasts.push(toast)
+
+ this.startLoop()
+
+ }
+
+ remove(toast) {
+
+ toast.removeFrom(this.container)
+ this.toasts.splice(this.toasts.indexOf(toast), 1)
+
+ if (this.toasts.length === 0) this.stopLoop()
+
+ }
+
+ startLoop() {
+
+ if (this.loop) return
+
+ this.loop = setInterval(()=>{
+ for (var i = this.toasts.length - 1; i > -1; i--) {
+ if (Date.now() > this.toasts[i].expires) {
+ this.remove(this.toasts[i])
+ }
+ }
+
+ },100)
+
+ }
+
+ stopLoop() {
+
+ if (!this.loop) return
+
+ clearInterval(this.loop)
+ this.loop = null
+
+ }
+
+
+}
+
+module.exports = new Notifications()
diff --git a/src/client/ui/scrollbar-color.js b/src/client/ui/scrollbar-color.js
new file mode 100644
index 00000000..6606903e
--- /dev/null
+++ b/src/client/ui/scrollbar-color.js
@@ -0,0 +1,27 @@
+var chroma = require('chroma-js')
+
+module.exports = (container)=>{
+
+ setTimeout(()=>{
+
+ var computedStyle = window.getComputedStyle(container),
+ alpha = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar')),
+ alphaOn = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar-on')),
+ color = computedStyle.getPropertyValue('--color-fill').trim()
+
+ if (color === 'transparent') {
+ // prevent chroma-js error
+ // irrelevant case, but still...
+ color = 'rgb(0, 0, 0)'
+ alpha = 0
+ alphaOn = 0
+ }
+
+ if (color) {
+ container.style.setProperty('--color-scrollbar', chroma(color).alpha(alpha).css())
+ container.style.setProperty('--color-scrollbar-on', chroma(color).alpha(alphaOn).css())
+ }
+
+ })
+
+}
diff --git a/src/client/ui/ui-colorpicker.js b/src/client/ui/ui-colorpicker.js
new file mode 100644
index 00000000..dc7b3576
--- /dev/null
+++ b/src/client/ui/ui-colorpicker.js
@@ -0,0 +1,119 @@
+var UiWidget = require('./ui-widget'),
+ Rgb = require('../widgets/pads/rgb'),
+ UiModal = require('./ui-modal'),
+ html = require('nanohtml'),
+ chroma = require('chroma-js'),
+ resize = require('../events/resize'),
+ locales = require('../locales')
+
+
+class ColorPicker extends UiWidget {
+
+ constructor() {
+
+ super({})
+
+ this.name = ''
+ this.value = ''
+
+ this.rgb = new Rgb({props: {
+ ...Rgb.defaults()._props(),
+ type: 'rgb',
+ width: 'auto',
+ height: 'auto',
+ alphaStroke: 0,
+ snap: true,
+ alpha: true
+ }, parent: this})
+ this.rgb.container.classList.add('not-editable')
+
+ this.modal = new UiModal({
+ width: 280,
+ height: 320,
+ closable: true,
+ title: '',
+ hide: true,
+ html: true,
+ content: html`
+
+ ${this.rgb.container}
+
+
${locales('inspector_color_apply')}
+
${locales('inspector_color_confirm')}
+
+
+ `,
+ enterKey: this.confirm.bind(this)
+ })
+
+ DOM.get(this.modal.container, '.color-confirm')[0].addEventListener('click', this.confirm.bind(this))
+ DOM.get(this.modal.container, '.color-apply')[0].addEventListener('click', this.apply.bind(this))
+
+ this.rgb.on('change', (e)=>{
+ e.stopPropagation = true
+ })
+ // this.rgb.on('dragend', (e)=>{
+ // this.value = chroma(this.rgb.value).hex()
+ // this.trigger('change')
+ // })
+
+ this.opened = 0
+ this.label = DOM.get(this.modal.container, '.title')[0]
+
+ }
+
+ open() {
+
+ this.label.innerHTML = this.name
+ this.modal.open()
+ resize.check(this.rgb.container)
+ this.opened = 1
+
+ }
+
+ close() {
+
+ this.modal.close()
+ this.setName()
+ this.opened = 0
+
+ }
+
+ apply() {
+
+ this.value = chroma(this.rgb.value).hex()
+ this.trigger('change')
+
+ }
+
+ confirm() {
+
+ this.value = chroma(this.rgb.value).hex()
+ this.trigger('change')
+ this.close()
+
+ }
+
+ isVisible() {
+
+ return true
+
+ }
+
+ setName(n = '') {
+
+ this.name = n
+
+ }
+
+ setValue(v) {
+
+ if (v === 'transparent') v = '#00000000'
+
+ this.rgb.setValue(chroma(v).rgba())
+
+ }
+
+}
+
+module.exports = ColorPicker
diff --git a/src/client/ui/ui-dragresize.js b/src/client/ui/ui-dragresize.js
new file mode 100644
index 00000000..1d745f03
--- /dev/null
+++ b/src/client/ui/ui-dragresize.js
@@ -0,0 +1,188 @@
+var UiWidget = require('./ui-widget'),
+ html = require('nanohtml'),
+ Tab, Root
+
+class UiDragResize extends UiWidget {
+
+ constructor(options) {
+
+ Tab = require('../widgets/containers/tab')
+ Root = require('../widgets/containers/root')
+
+ super(options)
+
+ this.container = html`
+
+ `
+
+
+ this.initLeft = 0
+ this.initTop = 0
+ this.initWidth = 0
+ this.initHeight = 0
+
+ this.left = 0
+ this.top = 0
+ this.width = 0
+ this.height = 0
+
+ this.widgets = []
+ this.mounted = false
+
+ this.handles = DOM.get(this.container, '.handle')
+ this.dragging = null
+
+ this.on('draginit', (event)=>{
+
+ var node = event.firstTarget
+ if (event.shiftKey || !this.handles.includes(node)) return
+
+ this.initLeft = this.left
+ this.initTop = this.top
+ this.initWidth = this.width
+ this.initHeight = this.height
+ this.matrix = ''
+
+ this.container.classList.add('dragging')
+ this.dragging = node.getAttribute('data-action').split(',')
+ delete event.traversingStack
+ delete event.traversing
+
+ }, {element: this.container})
+
+ this.on('drag', (event)=>{
+
+ if (!this.dragging) return
+
+ for (var k of this.dragging) {
+
+ switch (k) {
+ case 'left':
+ case 'width':
+ this[k] += event.movementX / PXSCALE
+ break
+ case 'top':
+ case 'height':
+ this[k] += event.movementY / PXSCALE
+ break
+
+ }
+
+ }
+
+ this.updateCss(true)
+
+
+ }, {element: this.container})
+
+
+ this.on('dragend', (event)=>{
+
+ var node = event.firstTarget
+ if (!this.handles.includes(node)) return
+
+ this.container.classList.remove('dragging')
+ this.left = Math.max(0, this.left)
+ this.top = Math.max(0, this.top)
+ this.trigger(this.dragging.indexOf('left') > -1 ? 'move' : 'drag-resize', this)
+ this.dragging = null
+
+ }, {element: this.container})
+
+ window.addEventListener('resize', ()=>{
+ if (this.mounted) this.updateRectangle()
+ })
+
+ // this.handles[0]._ignore_css_transforms = true
+
+ }
+
+ clear() {
+
+ if (!this.mounted) return
+
+ this.container.parentNode.removeChild(this.container)
+ this.mounted = false
+ this.widgets = []
+
+
+ }
+
+ create(widgets) {
+
+ this.clear()
+
+ this.widgets = widgets.slice().filter(w=>w.getProp('visible') && !(w instanceof Tab) && !(w instanceof Root))
+
+ if (!this.widgets.length) return
+
+ this.updateRectangle()
+
+ this.widgets[0].parentNode.appendChild(this.container)
+ this.mounted = true
+
+
+ }
+
+ updateRectangle() {
+
+ var widgets = this.widgets,
+ widget = widgets[0]
+
+ var handlesVisibility = [
+ widget.parent.getProp('layout') === 'default', // nw
+ widget.parent.getProp('layout').match(/horizontal|default/), // e
+ widget.parent.getProp('layout').match(/vertical|default/), // s
+ ]
+ handlesVisibility.push(handlesVisibility[1] && handlesVisibility[2]) // se
+
+ for (var i in handlesVisibility) {
+ this.handles[i].style.display = handlesVisibility[i] ? '' : 'none'
+ }
+
+ var lefts = widgets.map(w => w.container.offsetLeft),
+ tops = widgets.map(w => w.container.offsetTop),
+ rights = widgets.map(w => w.container.offsetLeft + w.container.offsetWidth),
+ bottoms = widgets.map(w => w.container.offsetTop + w.container.offsetHeight)
+
+ this.left = Math.min(...lefts) / PXSCALE
+ this.top = Math.min(...tops) / PXSCALE
+ this.width = (Math.max(...rights) - Math.min(...lefts)) / PXSCALE
+ this.height = (Math.max(...bottoms) - Math.min(...tops)) / PXSCALE
+
+ // this.cssTransform = widget.cssTransform || 'none'
+ // this.cssTransformOrigin = widget.cssTransformOrigin
+
+ this.updateCss()
+
+ }
+
+ updateCss(grid) {
+
+ for (let k of ['top', 'left', 'width', 'height']) {
+
+ var val = this[k]
+
+ if (k === 'width' || k === 'height') val = Math.max(10 * PXSCALE, val)
+ if (grid && this.dragging.includes(k)) {
+ val = Math.round(val / GRIDWIDTH) * GRIDWIDTH
+ }
+
+ this.container.style.setProperty('--' + k, val + 'rem')
+
+ // this.container.style.transform = this.cssTransform
+ // this.container.style.transformOrigin = this.cssTransformOrigin
+
+ }
+
+ }
+
+}
+
+module.exports = UiDragResize
diff --git a/src/client/ui/ui-filebrowser.js b/src/client/ui/ui-filebrowser.js
new file mode 100644
index 00000000..e448e957
--- /dev/null
+++ b/src/client/ui/ui-filebrowser.js
@@ -0,0 +1,212 @@
+var locales = require('../locales'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ ipc = require('../ipc'),
+ doubleClick = require('../events/double-click'),
+ {icon} = require('./utils'),
+ UiModal = require('./ui-modal'),
+ keyboardJS = require('keyboardjs/dist/keyboard.min.js')
+
+
+module.exports = function UiFilebrowser(options, callback) {
+
+ var save = options.save,
+ saveInputFocus = undefined,
+ previousKbContext = keyboardJS.getContext()
+
+ var popup = new UiModal({
+ height: 360,
+ closable: true,
+ html: true,
+ title: locales(save ? 'remotesave_save' : 'remotesave_open'),
+ hide: true
+ })
+
+ var container = DOM.get(popup.container, '.popup-content')[0],
+ browser = html`
`,
+ ariane = html`
`,
+ list = html``,
+ saveInput = html` `,
+ actions = html`
+
+ ${saveInput}
+
${raw(icon('times'))} Cancel
+ ${
+ save ?
+ html`
${raw(icon('save'))} Save
` :
+ html`
${raw(icon('folder-open'))} Open
`
+ }
+
+ `
+
+ var files = [],
+ path = ''
+
+ var extRe = options.extension ? new RegExp('.*\\.' + options.extension + '$') : /.*/
+
+ if (save) {
+ saveInput.addEventListener('change', ()=>{
+ if (!saveInput.value.match(extRe)) saveInput.value += '.' + options.extension
+ })
+ saveInput.addEventListener('focus', ()=>{
+ saveInputFocus = true
+ })
+ list.addEventListener('change', ()=>{
+ saveInputFocus = false
+ var choice = DOM.get(list, ':checked')[0]
+ if (choice && choice.classList.contains('file')) {
+ saveInput.value = choice.value
+ }
+ })
+ }
+
+ doubleClick(list, submit, {click: true})
+
+ function submit(){
+
+ var choice = DOM.get(list, ':checked')[0]
+
+ if (!choice && (!save || !saveInput.value) && !options.loadDir) return
+
+ if (choice && choice.classList.contains('folder') && (!save || !saveInputFocus)) {
+ ipc.send('listDir', {path: [path, choice.value]})
+ } else {
+ if (save) {
+ if (files.some(x=>x.name===saveInput.value)) {
+ if (!confirm(locales('remotesave_overwrite'))) return
+ }
+ callback([path, saveInput.value])
+ popup.close()
+ } else {
+ callback([path, choice ? choice.value : ''])
+ popup.close()
+ }
+ }
+
+ }
+
+ actions.addEventListener('click', (e)=>{
+ if (e.target.classList.contains('submit')) {
+ submit()
+ } else if ((e.target.classList.contains('cancel'))){
+ popup.close()
+ }
+ })
+
+ function keyDownHandler(e){
+
+ if (e.keyCode === 13) {
+ if (save) {
+ document.addEventListener('keyup', keyUpHandler)
+ } else {
+ submit()
+ }
+ } else if (e.target === saveInput) {
+ return
+ } else if (e.keyCode === 8) {
+ list.childNodes[0].firstElementChild.checked = true
+ submit()
+ } else if (e.key.length === 1) {
+ var letter = e.key.toLowerCase(),
+ current = DOM.get(list, ':checked')[0],
+ minIndex = -1,
+ index = -1
+
+ if (current) minIndex = DOM.index(current.parentNode)
+
+ for (let i in files) {
+ if (files[i].name[0].toLowerCase() === letter && !list.childNodes[i].firstElementChild.checked) {
+ if (index === -1) index = i
+ if (minIndex !== -1 && i < minIndex) continue
+ index = i
+ break
+ }
+ }
+
+ if (index !== -1) {
+ list.childNodes[index].firstElementChild.click()
+ list.childNodes[index].firstElementChild.focus()
+ }
+ }
+ }
+ function keyUpHandler(e){
+
+ if (e.keyCode === 13) {
+ setTimeout(submit, 100)
+ document.removeEventListener('keyup', keyUpHandler)
+ }
+
+ }
+
+ document.addEventListener('keydown', keyDownHandler)
+
+ ipc.on('listDir', (data)=>{
+
+ ariane.textContent = path = data.path
+
+ files = data.files.filter(x=>x.folder || x.name.match(extRe))
+
+
+ function alphaSort(a, b){
+ // convert to strings and force lowercase
+ a = typeof a.name === 'string' ? a.name.toLowerCase() : a.name.toString()
+ b = typeof b.name === 'string' ? b.name.toLowerCase() : b.name.toString()
+ return a.localeCompare(b)
+ }
+
+ var fo = files.filter(x=>x.folder),
+ fi = files.filter(x=>!x.folder)
+
+ fo.sort(alphaSort)
+ fi.sort(alphaSort)
+
+ files = fo.concat(fi)
+
+ files.unshift({
+ name: '..',
+ folder: true
+ })
+
+
+ browser.removeChild(list)
+ list.innerHTML = ''
+ for (let i in files) {
+ var file = files[i]
+ list.appendChild(html`
+
+
+
${raw(icon(file.folder ? 'folder' : 'osc'))} ${file.name}
+
+ `)
+ }
+
+
+ browser.insertBefore(list, actions)
+
+
+ if (save && saveInputFocus === undefined) {
+ saveInput.focus()
+ } else {
+ list.childNodes[0].firstElementChild.focus()
+ }
+
+ }, {context: popup})
+
+ popup.on('close', ()=>{
+ ipc.off('listDir', null, popup)
+ document.removeEventListener('keydown', keyDownHandler)
+ document.removeEventListener('keyup', keyUpHandler)
+ keyboardJS.setContext(previousKbContext)
+ })
+
+ browser.appendChild(ariane)
+ browser.appendChild(list)
+ browser.appendChild(actions)
+ container.appendChild(browser)
+
+ ipc.send('listDir', {extension: options.extension, path: options.directory ? [options.directory] : null})
+
+ popup.open()
+ keyboardJS.setContext('filebrowser')
+
+}
diff --git a/src/client/ui/ui-fileupload.js b/src/client/ui/ui-fileupload.js
new file mode 100644
index 00000000..126dd343
--- /dev/null
+++ b/src/client/ui/ui-fileupload.js
@@ -0,0 +1,41 @@
+var locales = require('../locales'),
+ uiLoading = require('./ui-loading'),
+ html = require('nanohtml'),
+ SINGLETON = null,
+ CONTAINER = null
+
+module.exports = function uiFileUpload(types, ok, error) {
+
+ if (!CONTAINER) CONTAINER = DOM.get('osc-modal-container')[0]
+
+ if (SINGLETON) CONTAINER.removeChild(SINGLETON)
+
+ SINGLETON = html` `
+
+ CONTAINER.appendChild(SINGLETON)
+
+ SINGLETON.addEventListener('change',function(e){
+
+
+ var reader = new FileReader(),
+ file = e.target.files[0]
+
+ uiLoading(locales('loading_upload'))
+
+ reader.onerror = reader.onabort = function() {
+ loader.close()
+ error()
+ }
+
+ reader.onload = function(e) {
+ uiLoading(false)
+ ok(file.path, e.target.result)
+ }
+
+ reader.readAsText(file, 'utf-8')
+
+ })
+
+ SINGLETON.click()
+
+}
diff --git a/src/client/ui/ui-inspector-field.js b/src/client/ui/ui-inspector-field.js
new file mode 100644
index 00000000..e7cd7f40
--- /dev/null
+++ b/src/client/ui/ui-inspector-field.js
@@ -0,0 +1,130 @@
+var UiWidget = require('./ui-widget'),
+ {categories} = require('../widgets/'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ {icon} = require('../ui/utils'),
+ chroma = require('chroma-js')
+
+
+class UiInspectorField extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.name = options.name
+ this.widget = options.widget
+ this.value = options.value
+ this.default = options.default
+ this.tabIndex = options.tabIndex
+
+ this.container = html` `
+ this.label = this.container.appendChild(html`${this.name} `)
+
+ if (this.name === 'type' || this.name === 'widgetType') this.createTypeSelect()
+ else this.createInput()
+
+ }
+
+ createTypeSelect() {
+
+
+ if (this.widget.props.type == 'tab' || this.widget.props.type == 'root') {
+ this.container.appendChild(html`
+
+ `)
+ return
+ }
+
+ this.createInput()
+
+ var select = html` `
+
+ for (let cname in categories) {
+
+ var optGroup = html` `
+
+ for (let wtype of categories[cname]) {
+ optGroup.appendChild(html`${wtype} `)
+ }
+
+ select.appendChild(optGroup)
+
+ }
+
+ var wrapper = html` `
+ wrapper.appendChild(select)
+ this.container.appendChild(wrapper)
+
+ }
+
+ createInput() {
+
+
+ var stringValue = typeof this.value !== 'string' ?
+ JSON.stringify(this.value, null, ' ').replace(/\n\s\s\s\s/g, ' ').replace(/\n\s\s(\}|\])/g, ' $1') : this.value
+
+
+ var input = html``
+
+ if (this.default.value === 'auto' && stringValue === 'auto') {
+ input.placeholder = stringValue
+ } else {
+ input.textContent = stringValue
+ }
+
+ this.container.appendChild(input)
+
+
+ if (this.default.choices) {
+
+ let wrapper = html` `,
+ select = wrapper.appendChild(html` `)
+ for (let choice of this.default.choices) {
+ select.appendChild(html`${choice} `)
+ }
+
+ this.container.appendChild(wrapper)
+
+ } else if (this.default.type.includes('boolean')) {
+
+ let toggle = html`
+
+ ${raw(icon('check'))}
+
+ `
+
+ this.container.appendChild(toggle)
+
+ } else if (this.name.includes('color')) {
+
+ let style = window.getComputedStyle(this.widget.container),
+ colorData = this.widget.constructor.cssVariables.find(x=>x.js === this.name),
+ val = 'transparent'
+
+ try {
+ val = chroma(style.getPropertyValue(colorData.css).trim()).hex('rgba')
+ } catch(e) {}
+
+ let picker = html` `
+
+ this.container.appendChild(picker)
+
+ } else if (stringValue === 'auto' && this.widget.constructor.cssVariables.some(x=>x.js === this.name)) {
+
+ let style = window.getComputedStyle(this.widget.container),
+ data = this.widget.constructor.cssVariables.find(x=>x.js === this.name),
+ val = style.getPropertyValue(data.css).trim()
+
+ if (data.toJs) val = data.toJs(val)
+
+ this.container.appendChild(html`${val}
`)
+
+ }
+
+
+ }
+
+}
+
+module.exports = UiInspectorField
diff --git a/src/client/ui/ui-inspector.js b/src/client/ui/ui-inspector.js
new file mode 100644
index 00000000..2338218f
--- /dev/null
+++ b/src/client/ui/ui-inspector.js
@@ -0,0 +1,309 @@
+var UiWidget = require('./ui-widget'),
+ UiInspectorField = require('./ui-inspector-field'),
+ UiColorPicker = require('./ui-colorpicker'),
+ UiModal = require('./ui-modal'),
+ morph = require('nanomorph'),
+ {defaults} = require('../widgets/'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+
+
+
+class UiInspector extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.mounted = false
+
+ this.expandedCategories = ['_widget']
+
+ this.widget = null
+
+ this.container.addEventListener('fast-click', (e)=>{
+
+ if (e.target.classList.contains('category-header')) {
+ var name = e.target.getAttribute('data-name'),
+ expandedIndex = this.expandedCategories.indexOf(name)
+ e.target.parentNode.classList.toggle('expanded', expandedIndex < 0)
+ if (expandedIndex > -1) {
+ this.expandedCategories.splice(expandedIndex, 1)
+ } else {
+ this.expandedCategories.push(name)
+ }
+
+ }
+
+ })
+
+ this.colorPicker = new UiColorPicker()
+ this.colorPicker.on('change', ()=>{
+ var textarea = DOM.get(this.container, `textarea[name="${this.colorPicker.name}"]`)
+ if (textarea) {
+ textarea[0].value = this.colorPicker.value
+ DOM.dispatchEvent(textarea[0], 'change')
+ }
+ })
+
+ this.container.addEventListener('click', (e)=>{
+
+ var node = e.target
+
+ if (node.tagName === 'OSC-INSPECTOR-CHECKBOX') {
+
+ var name = node.getAttribute('name')
+
+ var textarea = DOM.get(this.container, `textarea[name="${name}"]`)
+ if (textarea) {
+ textarea[0].value = !node.classList.contains('on')
+ DOM.dispatchEvent(textarea[0], 'change')
+ }
+
+ } else if (node.tagName === 'OSC-INSPECTOR-COLOR') {
+
+ this.colorPicker.setName(node.getAttribute('name'))
+ this.colorPicker.setValue(node.getAttribute('value'))
+ this.colorPicker.open()
+
+ } else if (node.tagName === 'LABEL') {
+
+ this.help(node.textContent)
+
+ }
+
+ })
+
+
+ this.container.addEventListener('change', this.onChange.bind(this))
+ this.container.addEventListener('keydown', this.onKeydown.bind(this))
+ this.container.addEventListener('input', this.textAutoHeight.bind(this))
+ this.container.addEventListener('focus', this.textAutoHeight.bind(this))
+
+
+ this.lock = false
+ this.clearTimeout = null
+
+ this.helpModalOpened = false
+
+ }
+
+ clear() {
+
+ this.clearTimeout = setTimeout(()=>{
+ this.widget = null
+ this.container.innerHTML = ''
+ this.mounted = false
+ this.clearTimeout = null
+ this.colorPicker.close()
+ })
+
+ }
+
+ inspect(widgets) {
+
+ if (this.clearTimeout) {
+ clearTimeout(this.clearTimeout)
+ this.clearTimeout = null
+ }
+
+ var content = html`
`
+
+ var widget = widgets[0],
+ props = defaults[widget.props.type],
+ tabIndex = 1000
+
+ this.widget = widget
+
+ let category
+
+ for (let propName in props) {
+
+ if (propName === '_children' || propName === 'tabs' || propName === 'widgets' || propName === '_props') continue
+
+ let field,
+ shared = true
+
+ for (var w of widgets) {
+ if (defaults[w.props.type][propName] === undefined) {
+ shared = false
+ }
+ }
+
+ if (!shared) continue
+
+
+ if (propName.indexOf('_separator') > -1) {
+
+ field = html`${props[propName]}
`
+
+ } else if (propName.indexOf('_') === 0) {
+
+ if (category) content.appendChild(category)
+
+ category = html` `
+
+ field = html``
+
+ } else if (widget.props[propName] === undefined) {
+
+ continue
+
+ } else {
+
+ field = new UiInspectorField({
+ parent: this,
+ widget: widget,
+ name: propName,
+ value: widget.props[propName],
+ default: defaults[w.props.type][propName],
+ tabIndex: tabIndex++
+ }).container
+
+ if (!field) continue
+
+ }
+ if (category) {
+ category.appendChild(field)
+ } else {
+ content.appendChild(field)
+ }
+
+
+ }
+
+ if (category) content.appendChild(category)
+
+ this.lock = true
+
+ if (this.mounted) {
+ morph(this.container.firstChild, content)
+ } else {
+ this.container.appendChild(content)
+ }
+
+ this.mounted = true
+ this.lock = false
+
+ if (this.colorPicker.opened) {
+
+ var picker = DOM.get(this.container, `osc-inspector-color[name="${this.colorPicker.name}"]`)
+ if (picker && picker[0]) {
+ this.colorPicker.setValue(picker[0].getAttribute('value'))
+ } else {
+ this.colorPicker.close()
+ }
+
+ }
+
+
+ }
+
+ onChange(event) {
+
+ if (this.lock) return
+
+ this.lock = true
+
+ var input = event.target
+
+ input.blur()
+
+ var v
+ var str = input.value.replace(/[‟“”]/g, '"').replace(/[‘’]/g, '\'') // convert invalid quote characters
+
+ try {
+ v = JSON.parseFlex(str)
+ if (typeof v === 'string') {
+ // escape backslashes in simple strings only
+ v = JSON.parseFlex(str.replace(/\\/g, '__BACKSLASH__'))
+ v = v.replace(/__BACKSLASH__/g, '\\')
+ }
+ } catch(err) {
+ v = str
+ }
+
+ this.trigger('update', {
+ propName: input.name,
+ value: v
+ })
+
+ this.lock = false
+ }
+
+ onKeydown(event) {
+
+ var input = event.target
+
+ if (event.keyCode === 13 && !event.shiftKey) {
+ event.preventDefault()
+ DOM.dispatchEvent(input, 'change')
+ }
+
+ }
+
+ textAutoHeight(event) {
+
+ var input = event.target
+
+ input.setAttribute('rows',0)
+ input.setAttribute('rows', input.value.split('\n').length)
+
+ }
+
+ help(name) {
+
+ var defaultValue = defaults[this.widget.getProp('type')][name],
+ dynamic = this.widget.isDynamicProp(name),
+ htmlHelp = Array.isArray(defaultValue.help) ? defaultValue.help.join(' ').replace(/ -/g, '-') : defaultValue.help
+
+ htmlHelp = htmlHelp ? html`${raw(htmlHelp.replace(/`([^`]*)`/g, '$1'))}
` : ''
+
+ DOM.each(htmlHelp, 'a', (el)=>{
+ el.target = '_blank'
+ })
+
+ var computedValue = this.widget.getProp(name)
+
+ if (typeof computedValue === 'string') {
+ try {
+ computedValue = JSON.stringify(JSON.parse(computedValue), null, ' ')
+ } catch(e) {}
+ } else {
+ computedValue = JSON.stringify(computedValue, null, ' ')
+ }
+
+ var modal = new UiModal({closable: true, title: html`${name} `, html: true, content: html`
+
+
+
+
+ ${htmlHelp}
+
+
+
Computed value: ${computedValue || 'empty'}
+
+
+ `})
+
+
+ this.helpModalOpened = true
+ modal.on('close', ()=>{
+ this.helpModalOpened = false
+ })
+
+ }
+
+}
+
+module.exports = UiInspector
diff --git a/src/client/ui/ui-loading.js b/src/client/ui/ui-loading.js
new file mode 100644
index 00000000..a9093b7a
--- /dev/null
+++ b/src/client/ui/ui-loading.js
@@ -0,0 +1,21 @@
+var notifications = require('./notifications'),
+ loading = null, timeout = null
+
+module.exports = function uiLoading(title) {
+
+ if (title === false && loading) {
+ clearTimeout(timeout)
+ timeout = setTimeout(()=>{
+ notifications.remove(loading)
+ loading = null
+ }, 500)
+ } else if (title !== false) {
+ notifications.add({
+ id: 'LOADING',
+ icon: 'spinner fa-spin',
+ message: title
+ })
+ loading = notifications.toasts[notifications.toasts.length - 1]
+ }
+
+}
diff --git a/src/client/ui/ui-modal.js b/src/client/ui/ui-modal.js
new file mode 100644
index 00000000..45a44e56
--- /dev/null
+++ b/src/client/ui/ui-modal.js
@@ -0,0 +1,105 @@
+var UiWidget = require('./ui-widget'),
+ {icon} = require('./utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ MODAL_SINGLETON = null,
+ MODAL_CONTAINER = null
+
+class UiModal extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ if (!MODAL_CONTAINER) MODAL_CONTAINER = DOM.get('osc-modal-container')[0]
+
+ if (options.closable) {
+
+ if (MODAL_SINGLETON) MODAL_SINGLETON.close()
+ MODAL_SINGLETON = this
+
+ }
+
+ this.escKey = options.closable || options.escKey
+ this.enterKey = options.enterKey
+ this.state = 0
+
+ this.container = html`
+
+ `
+
+ if (options.width) this.container.style.setProperty('--width', options.width + 'rem')
+ if (options.height) this.container.style.setProperty('--height', options.height + 'rem')
+
+ if (options.closable) {
+ var closer = DOM.get(this.container, '.popup-title .closer')[0]
+ this.container.addEventListener('fast-click',(e)=>{
+ if (e.target === this.container || e.target === closer) {
+ e.detail.preventOriginalEvent = true
+ this.close()
+ }
+ })
+ }
+
+ if (this.escKey) {
+ this.escKeyHandler = ((e)=>{
+ if (e.keyCode==27) this.close()
+ }).bind(this)
+ }
+
+ if (this.enterKey) {
+ this.enterKeyHandler = ((e)=>{
+ if (e.keyCode == 13) this.enterKey.call(this, e)
+ }).bind(this)
+ }
+
+ if (!options.hide) this.open()
+
+
+ }
+
+
+
+ close() {
+
+ if (!this.state) return
+ this.state = 0
+
+ if (this.escKey) document.removeEventListener('keydown', this.escKeyHandler)
+ if (this.enterKey) document.removeEventListener('keydown', this.enterKeyHandler)
+
+ MODAL_CONTAINER.removeChild(this.container)
+
+ this.trigger('close')
+
+ }
+
+ open() {
+
+ if (this.state) return
+ this.state = 1
+
+ if (this.escKey) document.addEventListener('keydown', this.escKeyHandler)
+ if (this.enterKey) document.addEventListener('keydown', this.enterKeyHandler)
+
+ MODAL_CONTAINER.appendChild(this.container)
+
+ this.trigger('open')
+ }
+
+}
+
+module.exports = UiModal
diff --git a/src/client/ui/ui-selectarea.js b/src/client/ui/ui-selectarea.js
new file mode 100644
index 00000000..a27a58df
--- /dev/null
+++ b/src/client/ui/ui-selectarea.js
@@ -0,0 +1,128 @@
+var html = require('nanohtml')
+
+class UiSelectArea {
+
+ constructor(selector, callback){
+
+ this.startX = 0
+ this.startY = 0
+ this.curX = 0
+ this.curY = 0
+
+ this.rectCoords = [0, 0, 0, 0]
+ this.rectSize = [0, 0]
+ this.elements = []
+
+ this.rect = document.body.appendChild(html`
`)
+
+ this.selector = selector
+ this.callback = callback
+
+ this.bindedMousedown = this.mousedown.bind(this)
+ this.bindedMousemove = this.mousemove.bind(this)
+ this.bindedMouseup = this.mouseup.bind(this)
+
+ }
+
+ mousedown(e) {
+ if (!e.shiftKey || event.button === 2) return
+ this.startX = this.curX = e.clientX
+ this.startY = this.curY = e.clientY
+ this.down = true
+ this.updateRect()
+ }
+
+ mousemove(e) {
+ if (!this.down) return
+ e.preventDefault()
+ e.stopPropagation()
+ this.curX = e.clientX
+ this.curY = e.clientY
+ this.updateRect()
+ }
+
+ mouseup(e) {
+ if (!this.down) return
+ this.down = false
+
+ if (this.rectSize[0] > 0 && this.rectSize[1] > 0) {
+ this.callback(this.getElements())
+ this.rect.classList.add('hidden')
+ }
+
+ this.elements = []
+
+ }
+
+ updateRect() {
+
+ var x0 = Math.min(this.startX, this.curX),
+ y0 = Math.min(this.startY, this.curY),
+ x1 = Math.max(this.startX, this.curX),
+ y1 = Math.max(this.startY, this.curY),
+ w = x1 - x0,
+ h = y1 - y0
+
+ if (w < 1 || h < 1) {
+ this.rect.classList.add('hidden')
+ } else {
+ this.rect.classList.remove('hidden')
+ this.rect.setAttribute('style', `width:${w}px;height:${h}px;left:${x0}px;top:${y0}px`)
+ }
+
+ this.rectSize = [w, h]
+ this.rectCoords = [x0, x1, y0, y1]
+
+ }
+
+ getElements(){
+
+ var [x0, x1, y0, y1] = this.rectCoords,
+ startEl = document.elementFromPoint(this.startX, this.startY),
+ elements = [startEl]
+
+ this.elements = DOM.each(document, this.selector, (el)=>{
+
+ var {left, right, top, bottom} = el.getBoundingClientRect()
+ if (!(
+ left > x1 ||
+ right < x0 ||
+ top > y1 ||
+ bottom < y0
+ )) {
+ if (el !== startEl) elements.push(el)
+ }
+
+ })
+
+ // slower implementation...
+ // for (var x = x0; x <= x1; x += 10) {
+ // for (var y = y0; y <= y1; y += 10) {
+ // var el = document.elementFromPoint(x, y)
+ // if (elements.indexOf(el) < 0) elements.push(el)
+ // }
+ // }
+
+ return elements
+
+ }
+
+ enable() {
+
+ document.addEventListener('pointerdown', this.bindedMousedown)
+ document.addEventListener('pointermove', this.bindedMousemove, true)
+ document.addEventListener('pointerup', this.bindedMouseup)
+
+ }
+
+ disable() {
+
+ document.removeEventListener('pointerdown', this.bindedMousedown)
+ document.removeEventListener('pointermove', this.bindedMousemove, true)
+ document.removeEventListener('pointerup', this.bindedMouseup)
+
+ }
+
+}
+
+module.exports = UiSelectArea
diff --git a/src/client/ui/ui-sidepanel.js b/src/client/ui/ui-sidepanel.js
new file mode 100644
index 00000000..f2feb746
--- /dev/null
+++ b/src/client/ui/ui-sidepanel.js
@@ -0,0 +1,135 @@
+var UiWidget = require('./ui-widget'),
+ cache = require('../managers/cache')
+
+class UiSidePanel extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ if (options.label) DOM.get(this.container, 'osc-panel-header')[0].textContent = options.label
+
+ this.vertical = this.container.classList.contains('bottom') || this.container.classList.contains('top')
+ this.resizeDirection = this.container.classList.contains('left') || this.container.classList.contains('top') ? 1 : -1
+ this.resizeHandle = DOM.get(this.container, '.resize-handle')[0]
+ this.toggleButton = DOM.get(this.container, '.toggle-button')[0]
+ this.content = DOM.get(this.container, 'osc-panel-content')[0]
+
+ this.cacheKey = 'ui.' + options.selector
+
+ this.minWidth = options.size || 250
+ this.width = cache.get(this.cacheKey + '.width') || options.size || 250
+
+ this.disabled = false
+ this.minimized = cache.get(this.cacheKey + '.minimized') || false
+ this.init = false
+
+
+ this.on('draginit', (event)=>{
+
+ this.width = parseInt(this.container[this.vertical ? 'offsetHeight' : 'offsetWidth']) / PXSCALE
+
+ }, {element: this.resizeHandle})
+
+ this.on('drag', (event)=>{
+
+ this.width += this.resizeDirection * event[this.vertical ? 'movementY' : 'movementX'] / PXSCALE
+ this.updateWidth()
+
+ }, {element: this.resizeHandle})
+
+ this.on('dragend', (event)=>{
+
+ this.width = parseInt(this.container[this.vertical ? 'offsetHeight' : 'offsetWidth']) / PXSCALE
+ cache.set(this.cacheKey + '.width', this.width)
+ DOM.dispatchEvent(window, 'resize')
+
+ }, {element: this.resizeHandle})
+
+ this.toggleButton.addEventListener('click', ()=>{
+
+ if (this.disabled) return
+
+ if (this.minimized) this.restore()
+ else this.minimize()
+
+ })
+
+ this.updateWidth()
+ this.disable()
+
+ }
+
+ enable() {
+
+ this.container.classList.remove('disabled')
+ this.disabled = false
+
+ if (!this.minimized) this.open()
+
+ }
+
+ disable() {
+
+ this.container.classList.add('disabled')
+ this.disabled = true
+
+ this.close()
+
+ }
+
+ minimize() {
+
+ if (this.minimized) return
+
+ this.minimized = true
+ cache.set(this.cacheKey + '.minimized', true)
+
+ if (!this.disabled) this.close()
+
+
+ }
+
+ restore() {
+
+ if (!this.minimized) return
+
+ this.minimized = false
+ cache.set(this.cacheKey + '.minimized', false)
+
+ if (!this.disabled) this.open()
+
+
+ }
+
+ updateWidth() {
+
+ this.container.style[this.vertical ? 'height' : 'width'] = this.width + 'rem'
+
+ }
+
+ open() {
+
+ this.container.style[this.vertical ? 'height' : 'width'] = this.width + 'rem'
+ this.container.style[this.vertical ? 'minHeight' : 'minWidth'] = this.minWidth + 'rem'
+ this.container.classList.remove('minimized')
+
+ DOM.dispatchEvent(window, 'resize')
+
+ }
+
+ close() {
+
+ this.container.style[this.vertical ? 'height' : 'width'] = 0
+ this.container.style[this.vertical ? 'minHeight' : 'minWidth'] = 0
+ this.container.classList.add('minimized')
+
+ DOM.dispatchEvent(window, 'resize')
+
+ }
+
+}
+
+
+
+module.exports = UiSidePanel
diff --git a/src/client/ui/ui-toolbar.js b/src/client/ui/ui-toolbar.js
new file mode 100644
index 00000000..95fb7b8f
--- /dev/null
+++ b/src/client/ui/ui-toolbar.js
@@ -0,0 +1,279 @@
+var UiWidget = require('./ui-widget'),
+ ContextMenu = require('./context-menu'),
+ ipc = require('../ipc'),
+ locales = require('../locales'),
+ notifications = require('./notifications'),
+ fullscreen = require('./fullscreen'),
+ editor = require('../editor'),
+ sessionManager = require('../managers/session/'),
+ stateManager = require('../managers/state'),
+ {leftUiSidePanel, rightUiSidePanel} = require('../ui/')
+
+
+var recentSessions = [{label: locales('file_open_recent_wait'), class: 'disabled'}]
+var menuEntries = [
+
+ {
+ label: locales('session'),
+ action: [
+ {
+ label: locales('session_new'),
+ action: sessionManager.create.bind(sessionManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('file_open'),
+ action: sessionManager.browse.bind(sessionManager),
+ shortcut: 'mod + o',
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ label: locales('file_open_recent'),
+ action: recentSessions,
+ class: ()=>{return !recentSessions.length ? 'disabled' :''}
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('file_save'),
+ action: sessionManager.save.bind(sessionManager),
+ shortcut: 'mod + s',
+ class: ()=>{return READ_ONLY || sessionManager.session === null ? 'disabled' :''}
+ },
+ {
+ label: locales('file_save_as'),
+ action: sessionManager.saveAs.bind(sessionManager),
+ shortcut: 'mod + shift + s',
+ class: ()=>{return READ_ONLY || sessionManager.session === null ? 'disabled' :''}
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('file_import'),
+ action: sessionManager.import.bind(sessionManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ label: locales('file_export'),
+ action: sessionManager.export.bind(sessionManager),
+ class: ()=>{return READ_ONLY || sessionManager.session === null ? 'disabled' :''}
+ },
+
+ ]
+ },
+ {
+ label: locales('state'),
+ class: ()=>{return sessionManager.session === null ? 'disabled' : ''},
+ action: [
+ {
+ label: locales('state_store'),
+ action: stateManager.quickSave.bind(stateManager)
+ },
+ {
+ label: locales('state_recall'),
+ class: ()=>{return stateManager.quickState === null ? 'disabled' : ''},
+ action: stateManager.quickLoad.bind(stateManager)
+ },
+ {
+ label: locales('state_send'),
+ action: ()=>{
+ stateManager.send()
+ notifications.add({
+ icon: 'sliders-h',
+ message: locales('state_sendsuccess')
+ })
+ }
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('file_open'),
+ action: stateManager.browse.bind(stateManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ label: locales('file_save'),
+ action: stateManager.save.bind(stateManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ label: locales('file_save_as'),
+ action: stateManager.saveAs.bind(stateManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('file_import'),
+ action: stateManager.import.bind(stateManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ {
+ label: locales('file_export'),
+ action: stateManager.export.bind(stateManager),
+ class: ()=>{return READ_ONLY ? 'disabled' :''}
+ },
+ ]
+ },
+ {
+ label: locales('editor'),
+ class: ()=>{return sessionManager.session === null || READ_ONLY ? 'disabled' : ''},
+ action: [
+ {
+ label: locales('editor_enabled'),
+ class: ()=>{return 'toggle ' + (editor.enabled ? 'on' : 'off')},
+ action: ()=>{
+ if (editor.enabled) editor.disable()
+ else editor.enable()
+ },
+ shortcut: 'mod + e'
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('editor_grid'),
+ class: ()=>{return 'toggle ' + (editor.grid ? 'on' : 'off')},
+ action: editor.toggleGrid.bind(editor),
+ shortcut: 'mod + g'
+
+ },
+ {
+ label: locales('editor_tree'),
+ class: ()=>{return 'toggle ' + (leftUiSidePanel.minimized ? 'off' : 'on')},
+ action: ()=>{return leftUiSidePanel.minimized ? leftUiSidePanel.restore() : leftUiSidePanel.minimize()},
+ shortcut: 'mod + t'
+
+
+ },
+ {
+ label: locales('editor_inspector'),
+ class: ()=>{return 'toggle ' + (rightUiSidePanel.minimized ? 'off' : 'on')},
+ action: ()=>{return rightUiSidePanel.minimized ? rightUiSidePanel.restore() : rightUiSidePanel.minimize()},
+ shortcut: 'mod + i'
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('editor_percents'),
+ class: ()=>{return 'toggle ' + (editor.usePercents ? 'on' : 'off')},
+ action: ()=>{editor.usePercents = !editor.usePercents}
+ }
+ ]
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('fullscreen'),
+ class: ()=>{return 'toggle ' + (fullscreen.isFullscreen ? 'on' : 'off')},
+ action: ()=>{
+ if (fullscreen.isEnabled) fullscreen.toggle()
+ },
+ shortcut: 'f11'
+ }
+
+]
+
+if (navigator.userAgent.match(/Android|iPhone|iPad|iPod/i)) {
+
+ var NoSleep = require('nosleep.js'),
+ noSleep = new NoSleep(),
+ noSleepState = false
+
+ menuEntries.push({
+ label: locales('nosleep'),
+ class: ()=>{return 'toggle ' + (noSleepState ? 'on' : 'off')},
+ action:()=>{
+ noSleepState = !noSleepState
+ if (noSleepState) noSleep.disable()
+ else noSleep.enable()
+ }
+ })
+
+}
+
+
+
+
+
+class UiToolbar extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.menu = new ContextMenu({
+ position: [40, 1]
+ })
+ this.opened = false
+ this.entries = menuEntries
+ this.menu.bindShortcuts(menuEntries)
+
+ ipc.on('sessionList', (data)=>{
+ if (recentSessions.length) {
+ recentSessions.splice(0, 10)
+ }
+ for (let s of data) [
+ recentSessions.push({
+ label: s,
+ action: ()=>{sessionManager.requestOpen(s)}
+ })
+ ]
+ })
+
+ this.container.addEventListener('fast-click', (e)=>{
+ if (this.opened) this.close()
+ else this.open(e)
+ })
+
+ this.menu.on('close', ()=>{
+ setTimeout(()=>{
+ this.opened = false
+ this.toggleState()
+ })
+ })
+
+ }
+
+ open(e) {
+
+ if (this.opened) return
+
+ this.menu.open(e, menuEntries)
+
+ this.opened = true
+ this.toggleState()
+
+
+ }
+
+ close() {
+
+ if (this.opened) return
+
+ this.menu.close()
+
+ this.opened = false
+ this.toggleState()
+
+ }
+
+ toggleState() {
+
+ this.container.classList.toggle('on', this.opened)
+
+ }
+
+}
+
+
+module.exports = new UiToolbar({selector: 'osc-toolbar'})
diff --git a/src/client/ui/ui-tree.js b/src/client/ui/ui-tree.js
new file mode 100644
index 00000000..52b7b543
--- /dev/null
+++ b/src/client/ui/ui-tree.js
@@ -0,0 +1,197 @@
+var UiWidget = require('./ui-widget'),
+ html = require('nanohtml'),
+ doubleClick = require('../events/double-click'),
+ Sortable = require('sortablejs'),
+ morph = require('nanomorph'),
+ Root, Panel, Matrix, Keyboard, widgetManager,
+ init = false
+
+class UiTree extends UiWidget {
+
+ constructor(options) {
+
+ Root = require('../widgets/containers/root')
+ Panel = require('../widgets/containers/panel')
+ Matrix = require('../widgets/containers/matrix')
+ Keyboard = require('../widgets/containers/keyboard')
+ widgetManager = require('../managers/widgets')
+
+ super(options)
+
+ this.mounted = false
+ this.list = this.container.appendChild(html` `
+
+
+ this.expanded = {}
+
+ this.container.addEventListener('fast-click', (event)=>{
+
+ var node = event.target
+ if (node.classList.contains('toggle')) {
+ var exp = node.parentNode.classList.toggle('expanded')
+ if (exp) {
+ this.expanded[node.parentNode.getAttribute('data-widget')] = true
+ } else {
+ delete this.expanded[node.parentNode.getAttribute('data-widget')]
+ }
+ }
+
+
+ })
+
+ doubleClick(this.container, (event)=>{
+
+ var node = event.target
+ if (node.classList.contains('container')) {
+ var exp = node.classList.toggle('expanded')
+ if (exp) {
+ this.expanded[node.getAttribute('data-widget')] = true
+ } else {
+ delete this.expanded[node.getAttribute('data-widget')]
+ }
+ }
+
+ }, {ignoreEditorCapture: true})
+
+
+ this.sortables = []
+ this.sortCallback = (event)=>{
+ var widget = widgetManager.widgets[event.to.parentNode.getAttribute('data-widget')]
+ if (!widget) return
+ this.trigger('sorted', {
+ widget: widget,
+ oldIndex: event.oldIndex,
+ newIndex: event.newIndex
+ })
+ }
+
+ widgetManager.on('prop-changed', (e)=>{
+ console.log(e)
+ })
+
+ }
+
+ clear() {
+
+ this.list.innerHTML = ''
+ this.mounted = false
+ for (var s of this.sortables) {
+ s.destroy()
+ }
+ this.sortables = []
+
+ }
+
+ updateTree(selectedWidgets) {
+
+ for (var s of this.sortables) {
+ s.destroy()
+ }
+ this.sortables = []
+
+ var content = this.parseWidgets(widgetManager.getWidgetById('root')[0], selectedWidgets)
+
+ if (!content) return
+
+ // morph DOM
+ if (this.mounted) {
+ morph(this.list.firstChild, content)
+ } else {
+ this.list.appendChild(content)
+ }
+
+
+ // sortable lists
+ DOM.each(this.list, 'ol', (el)=>{
+
+ this.sortables.push(new Sortable(el, {
+ group: {
+ name: 'group-' + el.parentNode.getAttribute('data-widget'),
+ pull: false,
+ put: false
+ },
+ onEnd: this.sortCallback,
+ setData: (dataTransfer)=>{
+ dataTransfer.setDragImage(this.dragDummy, 0, 0)
+ },
+ }))
+ })
+
+ this.mounted = true
+
+
+ }
+
+ showWidget(widget) {
+
+ var node = DOM.get(this.list, `[data-widget="${widget.hash}"]`)
+ if (node) {
+ var parent = node[0].parentNode
+ while (parent !== this.list) {
+ if (parent.classList.contains('container')) {
+ parent.classList.add('expanded')
+ this.expanded[parent.getAttribute('data-widget')] = true
+ }
+ parent = parent.parentNode
+ }
+ node[0].scrollIntoView({block: 'center'})
+ }
+
+ }
+
+ select() {
+
+ // hint selection in folded containers
+ DOM.each(this.list, '.contains-editing', (element)=>{
+ element.classList.remove('contains-editing')
+ })
+ var selected = DOM.get(this.list, '.editing')[0]
+ if (selected) {
+ var node = selected.parentNode
+ while (node && node !== this.list) {
+ if (node.classList.contains('container')) {
+ node.classList.add('contains-editing')
+ }
+ node = node.parentNode
+ }
+ }
+ }
+
+ parseWidgets(widget, selectedWidgets, depth = 1) {
+
+ if (!widget) return
+
+ var selected = selectedWidgets.includes(widget),
+ id = widget.getProp('id'),
+ node = html`
+ ${id} `
+
+ if (widget instanceof Panel && !(widget instanceof Matrix || widget instanceof Keyboard)) {
+ node.insertBefore(html` `, node.childNodes[0])
+ node.classList.add('container')
+ if (this.expanded[widget.hash]) node.classList.add('expanded')
+ if (!init && widget instanceof Root) {
+ node.classList.add('expanded')
+ this.expanded[widget.hash] = true
+ init = true
+ }
+ var sublist = node.appendChild(html` `)
+ for (let child of widget.children) {
+ if (child) sublist.appendChild(this.parseWidgets(child, selectedWidgets, depth))
+ }
+
+ }
+
+ for (var h in this.expanded) {
+ if (!widgetManager.widgets[h]) delete this.expanded[h]
+ }
+
+ return node
+
+ }
+
+}
+
+module.exports = UiTree
diff --git a/src/client/ui/ui-widget.js b/src/client/ui/ui-widget.js
new file mode 100644
index 00000000..fa16cdbe
--- /dev/null
+++ b/src/client/ui/ui-widget.js
@@ -0,0 +1,16 @@
+var EventEmitter = require('../events/event-emitter')
+
+class UiWidget extends EventEmitter {
+
+ constructor(options={}) {
+
+ super()
+
+ this.container = options.selector ? DOM.get(options.selector)[0] : options.element
+ this.parent = options.parent
+
+ }
+
+}
+
+module.exports = UiWidget
diff --git a/src/client/ui/ui-workspace.js b/src/client/ui/ui-workspace.js
new file mode 100644
index 00000000..95c3d189
--- /dev/null
+++ b/src/client/ui/ui-workspace.js
@@ -0,0 +1,16 @@
+var UiWidget = require('./ui-widget'),
+ setScrollbarColor = require('./scrollbar-color')
+
+class UiWorkspace extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ setScrollbarColor(this.container)
+
+ }
+
+}
+
+module.exports = new UiWorkspace({selector: 'osc-workspace'})
diff --git a/src/client/ui/utils.js b/src/client/ui/utils.js
new file mode 100644
index 00000000..86c41985
--- /dev/null
+++ b/src/client/ui/utils.js
@@ -0,0 +1,15 @@
+
+module.exports = {
+
+
+ icon: function(i) {
+ var iclass = i.split('.').join(' fa-')
+ return ` `
+ },
+ iconify:function(string){
+ return String(string).replace(/\^[^\s]{2,}/g,(x)=>{return module.exports.icon(x.substring(1))})
+ },
+
+
+
+}
diff --git a/src/client/ui/zoom.js b/src/client/ui/zoom.js
new file mode 100644
index 00000000..8ed8e9f0
--- /dev/null
+++ b/src/client/ui/zoom.js
@@ -0,0 +1,29 @@
+// mousewheel zoom
+
+var mod = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
+
+document.addEventListener('wheel', function(event) {
+ if (event.ctrlKey) event.preventDefault()
+ if (event[mod]) {
+
+ event.preventDefault()
+
+ if (event.deltaY === 0) return
+
+ var d = - event.deltaY / (10 * Math.abs(event.deltaY))
+
+ PXSCALE = parseFloat(d) + parseFloat(PXSCALE)
+ document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+
+ DOM.dispatchEvent(window, 'resize')
+ }
+}, {passive: false})
+
+document.addEventListener('keydown', function(event){
+ if (event[mod] && (event.keyCode == 96 || event.keyCode == 48)) {
+ PXSCALE = INITIALZOOM
+ document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+
+ DOM.dispatchEvent(window, 'resize')
+ }
+}, {passive: true})
diff --git a/src/client/utils.js b/src/client/utils.js
new file mode 100644
index 00000000..e4e06d67
--- /dev/null
+++ b/src/client/utils.js
@@ -0,0 +1,48 @@
+module.exports = {
+
+ deepCopy: function(obj, decimals) {
+
+ var copy = obj
+
+ if (obj === null) {
+ return obj
+ }
+
+ if (typeof obj === 'object') {
+ copy = Array.isArray(obj) ? [] : {}
+ for (let key in obj) {
+ copy[key] = module.exports.deepCopy(obj[key], decimals)
+ }
+ } else if (typeof obj == 'number') {
+ return decimals === undefined ? copy : parseFloat(copy.toFixed(decimals))
+ }
+
+ return copy
+
+ },
+
+ deepEqual: function(a, b) {
+
+ var ta = typeof a,
+ tb = typeof b
+
+ if (ta !== tb) {
+ return false
+ } else if (ta === 'object') {
+ return JSON.stringify(a) === JSON.stringify(b)
+ } else {
+ return a === b
+ }
+
+ },
+
+ isJSON: function(str) {
+ // heuristic to avoid using JSON when unnecessary
+ // if the string doesn't start with one of these chars
+ // it's going to fail
+ // ref in source: https://github.com/douglascrockford/JSON-js
+ return ' \n+-eE{([0123456789tfn"'.indexOf(str[0]) !== -1
+
+ }
+
+}
diff --git a/src/client/widgets/basics/button.js b/src/client/widgets/basics/button.js
new file mode 100644
index 00000000..bac856f5
--- /dev/null
+++ b/src/client/widgets/basics/button.js
@@ -0,0 +1,252 @@
+var Widget = require('../common/widget'),
+ doubletab = require('../mixins/double_tap'),
+ html = require('nanohtml'),
+ {deepEqual, isJSON} = require('../../utils'),
+ {iconify} = require('../../ui/utils')
+
+class Button extends Widget {
+
+ static description() {
+
+ return 'On / off button.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+
+ _class_specific: 'button',
+
+ label: {type: 'string|boolean', value: 'auto', help: [
+ 'Set to `false` to hide completely',
+ '- Insert icons using the prefix ^ followed by the icon\'s name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)',
+ '- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal`',
+ ]},
+ vertical: {type: 'boolean', value: false, help: 'Set to `true` to display the text vertically'},
+ wrap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to wrap long lines automatically.',
+ ]},
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message. Must be different from `on`.',
+ ]},
+ mode: {type: 'string', value: 'toggle', choices: ['toggle', 'push', 'tap'], help: [
+ 'Interraction mode:',
+ '- `toggle` (classic on/off switch)',
+ '- `push` (press & release)',
+ '- `tap` (no release)'
+ ]},
+ doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the button require a double tap to be pushed instead of a single tap'},
+ colorTextOn: {type: 'string', value: 'auto', help: 'Defines the widget\'s text color when active.'},
+
+ }, [], {}, Button)
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.state = 0
+ this.active = false
+ this.pulse = null
+
+ var tap = this.getProp('mode') === 'tap',
+ push = this.getProp('mode') === 'push' || tap
+
+ if (push) {
+
+ if (this.getProp('doubleTap')) {
+
+ doubletab(this.widget, ()=>{
+
+ this.active = true
+ this.setValue(this.getProp('on'), {sync: true, send: true})
+
+ if (tap) this.container.classList.add('active')
+
+ })
+
+ } else {
+
+ this.on('draginit',()=>{
+
+ if (this.active) return
+
+ this.active = true
+ this.setValue(this.getProp('on'), {sync: true, send: true})
+
+ if (tap) this.container.classList.add('active')
+
+
+ }, {element: this.widget})
+
+ }
+
+ this.on('dragend',()=>{
+
+ if (!this.active) return
+
+ this.active = false
+
+ if (!tap) this.setValue(this.getProp('off'), {sync: true, send: true})
+ if (tap) this.container.classList.remove('active')
+
+ }, {element: this.widget})
+
+ } else {
+
+ if (this.getProp('doubleTap')) {
+
+ doubletab(this.widget, ()=>{
+
+
+ this.active = true
+ this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true})
+
+ })
+
+ } else {
+
+ this.on('draginit',()=>{
+
+ if (this.active) return
+
+ this.active = true
+ this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true})
+
+ }, {element: this.widget})
+
+ this.on('dragend',()=>{
+
+ this.active = false
+
+ }, {element: this.widget})
+
+ }
+
+ }
+
+
+
+ this.value = this.getProp('off')
+
+ this.label = html` `
+
+ if (this.getProp('wrap')) this.label.classList.add('wrap')
+ if (this.getProp('vertical')) this.label.classList.add('vertical')
+
+ this.updateLabel()
+
+ }
+
+
+
+ setValue(v, options={}) {
+
+ if (typeof v === 'string' && isJSON(v)) {
+ try {
+ v = JSON.parse(v )
+ } catch (err) {}
+ }
+
+ var newstate
+
+ if (deepEqual(v, this.getProp('on'))) {
+
+ newstate = 1
+
+ } else if (deepEqual(v, this.getProp('off'))) {
+
+ newstate = 0
+
+ }
+
+ if (newstate !== undefined) {
+
+ this.state = newstate
+ this.container.classList.toggle('on', this.state)
+ this.value = this.getProp(this.state ? 'on' : 'off')
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ // tap mode
+ if (newstate && this.getProp('mode') === 'tap' && !options.tapRelease) {
+
+ // reset value
+ this.setValue(this.getProp('off'), {sync: false, send: false, tapRelease: true})
+
+ // pulse
+ clearTimeout(this.pulse)
+ this.container.classList.remove('pulse')
+ setTimeout(()=>{
+ this.container.classList.add('pulse')
+ this.pulse = setTimeout(()=>{
+ this.container.classList.remove('pulse')
+ }, 150)
+ }, 16)
+
+ }
+
+ }
+
+
+
+ }
+
+ updateLabel() {
+
+ if (this.getProp('label') === false) {
+
+ if (this.widget.contains(this.label)) this.widget.removeChild(this.label)
+
+ } else {
+ this.label.innerHTML = this.getProp('label') == 'auto'?
+ this.getProp('id'):
+ iconify(String(this.getProp('label')).replace(/
+
+
+
+ `})
+
+ if (this.getProp('align') === 'left') this.widget.classList.add('left')
+ if (this.getProp('align') === 'right') this.widget.classList.add('right')
+
+ this.select = this.widget.appendChild(html` `)
+ this.text = DOM.get(this.widget, '.text')[0]
+
+ this.parseValues()
+
+ this.select.addEventListener('change', ()=>{
+ this.setValue(this.values[this.select.selectedIndex], {sync:true, send:true, fromLocal:true})
+ })
+
+ this.select.selectedIndex = -1
+ this.container.classList.add('noselect')
+
+ }
+
+ parseValues() {
+
+ super.parseValues()
+
+ this.select.innerHTML = ''
+ for (var i = 0; i < this.values.length; i++) {
+ this.select.appendChild(html`
+
+ ${this.keys[i]}
+
+ `)
+ }
+
+ }
+
+ setValue(v,options={}) {
+
+ var i = this.getIndex(v)
+
+ this.value = this.values[i]
+
+ if (!options.fromLocal) this.select.selectedIndex = i
+
+ this.text.textContent = i === -1 ? '' : this.select.options[i].textContent
+
+ if (document.activeElement === this.select && iOS) {
+ // force menu close on ios
+ this.select.blur()
+ }
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+
+ case 'values':
+ this.parseValues()
+ this.setValue(this.value)
+ return
+
+ }
+
+ return ret
+
+ }
+
+}
+
+Dropdown.dynamicProps = Dropdown.prototype.constructor.dynamicProps.concat(
+ 'values'
+)
+
+
+module.exports = Dropdown
diff --git a/src/client/widgets/basics/file.js b/src/client/widgets/basics/file.js
new file mode 100644
index 00000000..ffc760f3
--- /dev/null
+++ b/src/client/widgets/basics/file.js
@@ -0,0 +1,86 @@
+var Widget = require('../common/widget'),
+ html = require('nanohtml'),
+ uiFilebrowser = require('../../ui/ui-filebrowser')
+
+module.exports = class File extends Widget {
+
+ static description() {
+
+ return 'File/Folder selector (server-side).'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'file',
+
+ align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
+ directory: {type: 'string', value: 'auto', help: 'Default browsing directory'},
+ extension: {type: 'string', value: '*', help: 'Only display files with this extension'},
+ hidePath: {type: 'boolean', value: false, help: 'Set to `true` to only display the filename (the whole path will still be used as value)'},
+ allowDir: {type: 'boolean', value: false, help: 'Allow selecting a folder (by pressing "open" when no file is selected)'}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+
+ `})
+
+ if (this.getProp('align') === 'left') this.widget.classList.add('left')
+ if (this.getProp('align') === 'right') this.widget.classList.add('right')
+
+ this.text = DOM.get(this.widget, '.text')[0]
+ this.widget.addEventListener('fast-click', (e)=>{
+
+ if (e.capturedByEditor === true) return
+
+ uiFilebrowser({
+ extension: this.getProp('extension').replace(/^\.?(.*)$/, '$1'),
+ directory: this.getProp('directory') === 'auto' ? undefined : this.getProp('directory'),
+ loadDir: this.getProp('allowDir')
+ }, (path)=>{
+
+ this.setValue(path.join(path[0][0] === '/' ? '/' : '\\'), {
+ sync: true,
+ send: true
+ })
+
+ })
+ })
+
+ }
+
+
+ setValue(v, options={}) {
+
+ this.value = v
+
+ var sep = v[0] === '/' ? '/' : '\\'
+ if (this.getProp('hidePath')) {
+ if (v[v.length - 1] === sep) {
+ this.text.textContent = v.substr(0, v.length - 1).split(sep).pop() + sep
+ } else {
+ this.text.textContent = v.split(sep).pop()
+ }
+ } else {
+ this.text.textContent = v
+ }
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+
+
+
+}
diff --git a/src/client/widgets/basics/input.js b/src/client/widgets/basics/input.js
new file mode 100644
index 00000000..8e267277
--- /dev/null
+++ b/src/client/widgets/basics/input.js
@@ -0,0 +1,173 @@
+var Canvas = require('../common/canvas'),
+ {deepCopy} = require('../../utils'),
+ html = require('nanohtml')
+
+class Input extends Canvas {
+
+ static description() {
+
+ return 'Text input.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'input',
+
+ align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
+ unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
+ asYouType: {type: 'boolean', value: false, help: 'Set to `true` to make the input send its value at each keystroke'}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.value = ''
+ this.stringValue = ''
+ this.focused = false
+ this.tabKeyBlur = false
+
+ if (this.getProp('vertical')) this.widget.classList.add('vertical')
+ if (this.getProp('align') === 'left') this.widget.classList.add('left')
+ if (this.getProp('align') === 'right') this.widget.classList.add('right')
+
+
+ if (this.getProp('interaction')) {
+
+ this.widget.setAttribute('tabindex', 0)
+ this.widget.addEventListener('focus', this.focus.bind(this))
+ this.input = html` `
+ this.input.addEventListener('blur', (e)=>{
+ this.blur(this.tabKeyBlur)
+ this.tabKeyBlur = false
+ })
+ var asYouType = this.getProp('asYouType')
+ this.input.addEventListener('keydown', (e)=>{
+ if (e.keyCode === 13) this.blur() // enter
+ else if (e.keyCode === 27) this.blur(false) // esc
+ else if (e.keyCode === 9) this.tabKeyBlur = true // tab
+ else if (asYouType) {
+ setTimeout(()=>{
+ this.inputChange()
+ })
+ }
+ })
+
+ }
+
+ }
+
+ focus() {
+
+ if (this.focused) return
+ this.focused = true
+
+ this.widget.setAttribute('tabindex','-1')
+ this.input.value = this.stringValue
+ this.widget.insertBefore(this.input, this.canvas)
+ this.input.focus()
+ this.input.setSelectionRange(0, this.input.value.length)
+
+ }
+
+ blur(change=true) {
+
+ if (!this.focused) return
+ this.focused = false
+
+ if (change) this.inputChange()
+
+ this.widget.setAttribute('tabindex','0')
+ this.widget.removeChild(this.input)
+
+ }
+
+ inputChange() {
+
+ this.setValue(this.input.value, {sync:true, send:true})
+
+ }
+
+ resizeHandle(event){
+
+ super.resizeHandle(event)
+
+ // if (this.getProp('vertical')){
+ //
+ // var ratio = CANVAS_SCALING * this.scaling
+ //
+ // this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ // this.ctx.rotate(-Math.PI/2)
+ // this.ctx.translate(-this.height * ratio, 0)
+ //
+ //
+ // if (ratio != 1) this.ctx.scale(ratio, ratio)
+ // }
+
+
+ }
+
+ setValue(v, options={} ) {
+
+ try {
+ this.value = JSON.parse(v)
+ } catch (err) {
+ this.value = v
+ }
+
+ this.stringValue = this.getStringValue()
+ this.batchDraw()
+
+ if (options.send && !options.fromSync) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ draw() {
+
+ var v = this.stringValue,
+ width = this.width,
+ height = this.height
+
+ if (this.getProp('unit') && v.length) v += ' ' + this.getProp('unit')
+
+ this.clear()
+
+ this.ctx.fillStyle = this.cssVars.colorText
+
+ if (this.textAlign == 'center') {
+ this.ctx.fillText(v, Math.round(width/2), Math.round(height/2))
+ } else if (this.textAlign == 'right') {
+ this.ctx.fillText(v, width, Math.round(height/2))
+ } else {
+ this.ctx.fillText(v, 0, Math.round(height/2))
+ }
+
+ this.clearRect = [0, 0, width, height]
+
+ }
+
+ getStringValue() {
+ if (this.value === undefined) return ''
+ return typeof this.value != 'string' ?
+ JSON.stringify(deepCopy(this.value, this.decimals)).replace(/,/g, ', ') :
+ this.value
+ }
+
+}
+
+Input.dynamicProps = Input.prototype.constructor.dynamicProps
+ .filter(x=>x !== 'interaction')
+
+
+module.exports = Input
diff --git a/src/client/widgets/basics/menu-base.js b/src/client/widgets/basics/menu-base.js
new file mode 100644
index 00000000..4f5b9e73
--- /dev/null
+++ b/src/client/widgets/basics/menu-base.js
@@ -0,0 +1,48 @@
+var Widget = require('../common/widget'),
+ {deepEqual} = require('../../utils')
+
+class MenuBase extends Widget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.value = undefined
+ this.values = []
+ this.keys = []
+ this.objectInValues = false
+
+ }
+
+ parseValues() {
+
+ this.values = []
+ this.keys = []
+
+ var values = this.getProp('values') || []
+
+ if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
+ values = values !== '' ? [values] : []
+ }
+
+ this.values = !Array.isArray(values) ? Object.values(values) : values
+ this.keys = !Array.isArray(values) ? Object.keys(values) : this.values
+ this.objectInValues = this.values.some(x=>typeof x === 'object')
+
+ }
+
+ getIndex(value) {
+
+ var index = this.values.indexOf(value)
+ if (index === -1 && this.objectInValues) {
+ for (var i = 0; i < this.values.length; i++) {
+ if (deepEqual(value, this.values[i])) return i
+ }
+ }
+ return index
+
+ }
+
+}
+
+module.exports = MenuBase
diff --git a/src/client/widgets/basics/menu.js b/src/client/widgets/basics/menu.js
new file mode 100644
index 00000000..46b5cdd6
--- /dev/null
+++ b/src/client/widgets/basics/menu.js
@@ -0,0 +1,352 @@
+var MenuBase = require('./menu-base'),
+ {iconify} = require('../../ui/utils'),
+ doubletab = require('../mixins/double_tap'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Menu extends MenuBase {
+
+ static description() {
+
+ return 'Drag and drop menu with a circular or grid layout.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'menu',
+
+ size: {type: 'number|array', value: 200, help: [
+ '- If `layout` is `circular`: diameter (in px)',
+ '- Else: square size or `[width, height]` array',
+ ]},
+ textAlign: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
+ menuAlignV: {type: 'string', value: 'center', choices: ['center', 'top', 'bottom'], help: 'Set to `top` or `bottom` to change menu alignment (otherwise center)'},
+ menuAlignH: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change menu alignment (otherwise center)'},
+ layout: {type: 'string', value: 'circular', choices: ['circular', 'horizontal', 'vertical', 'grid'], help: [
+ 'Defines whether the menu\'s layout should be rendered in a circle or in a box'
+ ]},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ toggle: {type: 'boolean', value: false, help: 'Set to `true` to make the menu stay opened after mouse/touch release'},
+ doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the menu require a double tap to be opened instead of a single tap'},
+ values: {type: 'array|object', value: [1, 2, 3], help: [
+ '`Array` of possible values to switch between : `[1,2,3]`',
+ '`Object` of label:value pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ ]},
+ weights: {type: 'array', value: '', help: [
+ '`Array` of `number` defining the weights of each value in `values`',
+ 'Ignored when `mode` is `grid`'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+
+
+ `})
+
+ this.widget.classList.add('text-align-' + this.getProp('textAlign'))
+ this.widget.classList.add('menu-align-h-' + this.getProp('menuAlignH'))
+ this.widget.classList.add('menu-align-v-' + this.getProp('menuAlignV'))
+
+ this.menu = html` `
+ this.text = DOM.get(this.widget, '.text')[0]
+
+ this.opened = false
+
+ this.selected = -1
+
+ this.parseValues()
+
+ if (this.getProp('doubleTap')) {
+
+ doubletab(this.widget, (e)=>{
+ if (this.opened) return
+ this.open(e)
+ })
+
+ this.on('draginit',(e)=>{
+
+ if (this.opened && this.getProp('toggle')) {
+
+ this.selectValue(e)
+ this.submitValue()
+
+ }
+
+ }, {element: this.widget})
+
+
+ } else {
+
+ this.on('draginit',(e)=>{
+
+ if (this.opened && this.getProp('toggle')) {
+
+ this.selectValue(e)
+ this.submitValue()
+
+ } else if (!this.opened) {
+
+ this.open(e)
+
+ }
+
+ }, {element: this.widget})
+
+ }
+
+ if (!this.getProp('toggle')) {
+
+ this.on('drag',(e)=>{
+
+ this.selectValue(e, true)
+
+ }, {element: this.widget})
+
+ this.on('dragend',()=>{
+
+ if (!this.opened) return
+ this.submitValue()
+
+ }, {element: this.widget})
+
+ } else {
+
+ this.toggleCloseHandler = (e)=>{
+ if (!this.opened || this.menu.contains(e.target)) return
+ this.close()
+ }
+ document.addEventListener('fast-click', this.toggleCloseHandler)
+
+ }
+
+ this.setMode()
+ this.setSize()
+
+ }
+
+ open(e) {
+
+ if (this.opened) return
+
+ this.opened = true
+ this.fixParents()
+
+ this.container.classList.add('on')
+ this.widget.appendChild(this.menu)
+
+ }
+
+ close() {
+
+ if (!this.opened) return
+
+ this.opened = false
+ this.fixParents()
+ DOM.each(this.menu, '.active', (el)=>{el.classList.remove('active')})
+ this.container.classList.remove('on')
+ this.widget.removeChild(this.menu)
+
+ }
+
+ selectValue(e, drag) {
+
+ // touch hover fix
+ var node = drag && e.isTouch ? document.elementFromPoint(e.clientX, e.clientY)
+ : e.target
+
+ if (node === this.menu || !this.menu.contains(node)) {
+ DOM.each(this.menu, '.active', (el)=>{el.classList.remove('active')})
+ this.selected = -1
+ } else if (!node.classList.contains('active')) {
+ DOM.each(this.menu, '.active', (el)=>{el.classList.remove('active')})
+ node.classList.add('active')
+ this.selected = DOM.index(node)
+ }
+
+ }
+
+ submitValue(e) {
+
+ this.close()
+ if (this.selected > -1) {
+ this.setValue(this.values[this.selected], {send: true, sync: true})
+ }
+
+ }
+
+ parseValues() {
+
+ super.parseValues()
+
+ var nval = this.values.length,
+ circular = this.getProp('layout') === 'circular',
+ weights = this.getProp('weights'),
+ totalWeight
+
+ if (this.opened) this.widget.removeChild(this.menu)
+ this.menu.innerHTML = ''
+
+ weights = Array.isArray(weights) ? weights.slice(0, nval) : Array(nval).fill(1)
+ if (weights.length < nval) weights = weights.concat(Array(nval - weights.length).fill(1))
+ totalWeight = weights.reduce((a, b) => a + b, 0)
+
+ var ac = 0
+ for (var i = 0; i < nval; i++) {
+ let angle = Math.min(360 * weights[i] / totalWeight, 120),
+ skew = 90 - angle
+
+ this.menu.appendChild(html`
+
+
${raw(iconify(this.keys[i]))}
+
+ `)
+ ac+=angle
+
+ }
+
+ if (circular) this.menu.appendChild(html`
`)
+
+
+ this.setValue(this.value)
+
+ if (this.opened) this.widget.appendChild(this.menu)
+
+ }
+
+ setMode() {
+
+ var layout = this.getProp('layout')
+ this.container.classList.toggle('box', layout !== 'circular')
+ this.container.classList.toggle('circular', layout === 'circular')
+ this.container.classList.toggle('grid', layout === 'grid')
+ this.container.classList.toggle('vertical', layout === 'vertical')
+
+ if (layout === 'grid') {
+ var template = this.getProp('gridTemplate') || Math.round(this.values.length / 2)
+ this.menu.style.gridTemplate = template === parseInt(template) ? `none / repeat(${template}, 1fr)` : template
+ }
+
+ }
+
+ setSize() {
+
+ var size = this.getProp('size')
+ if (Array.isArray(size)) {
+ this.container.style.setProperty('--size', parseInt(size[0]) + 'rem')
+ this.container.style.setProperty('--size-box-w', parseInt(size[0]) + 'rem')
+ this.container.style.setProperty('--size-box-h', parseInt(size[1]) + 'rem')
+
+ } else {
+ this.container.style.setProperty('--size', parseInt(size) + 'rem')
+ this.container.style.setProperty('--size-box-w', parseInt(size) + 'rem')
+ this.container.style.setProperty('--size-box-h', parseInt(size) + 'rem')
+ }
+
+ }
+
+ fixParents() {
+
+ var parent = this.parent,
+ scrollX = 0,
+ scrollY = 0
+
+ while (parent && parent.props && !parent.getProp('type').match(/tab|root/)) {
+
+ parent.modalBreakout += (this.opened ? 1 : -1)
+ if (parent.modalBreakout > 0) parent.container.classList.add('modal-breakout')
+ else if (parent.modalBreakout === 0) parent.container.classList.remove('modal-breakout')
+ else parent.modalBreakout = 0
+
+ scrollX += parent.widget.scrollLeft
+ scrollY += parent.widget.scrollTop
+
+ parent = parent.parent
+ }
+
+ scrollX += parent.widget.scrollLeft
+ scrollY += parent.widget.scrollTop
+
+ this.container.style.setProperty('--parent-scroll-x', scrollX + 'px')
+ this.container.style.setProperty('--parent-scroll-y', scrollY + 'px')
+
+ }
+
+ setValue(v,options={}) {
+
+ var i = this.getIndex(v)
+
+ if (i !== -1) {
+ this.value = this.values[i]
+ this.selected = i
+ DOM.each(this.menu, '.on', (el)=>{el.classList.remove('on')})
+ DOM.get(this.menu, '.item')[i].classList.add('on')
+ this.text.innerHTML = iconify(this.keys[i])
+
+ }
+
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+
+ case 'size':
+ this.setSize()
+ return
+ case 'layout':
+ this.parseValues()
+ this.setMode()
+ return
+ case 'columns':
+ this.setMode()
+ return
+ case 'values':
+ this.parseValues()
+ return
+
+ }
+
+ return ret
+
+ }
+
+ onRemove() {
+
+ if (this.getProp('toggle')) {
+ document.removeEventListener('fast-click', this.toggleCloseHandler)
+ }
+ if (this.opened) {
+ this.close()
+ }
+ super.onRemove()
+
+ }
+
+}
+
+Menu.dynamicProps = Menu.prototype.constructor.dynamicProps.concat(
+ 'size',
+ 'layout',
+ 'columns',
+ 'values'
+)
+
+
+module.exports = Menu
diff --git a/src/client/widgets/basics/switch.js b/src/client/widgets/basics/switch.js
new file mode 100644
index 00000000..adef332d
--- /dev/null
+++ b/src/client/widgets/basics/switch.js
@@ -0,0 +1,133 @@
+var MenuBase = require('./menu-base'),
+ {iconify} = require('../../ui/utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Switch extends MenuBase {
+
+ static description() {
+
+ return 'Value selector button.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'switch',
+
+ layout: {type: 'string', value: 'vertical', choices: ['vertical', 'horizontal', 'grid'], help:''},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
+ '`Array` of possible values to switch between : `[1,2,3]`',
+ '`Object` of `"label":value` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ ]},
+ mode: {type: 'string', value: 'tap', choices: ['tap', 'slide', 'click'], help: [
+ 'Interraction mode:',
+ '- `tap`: activates when the pointer is down but prevents further scrolling',
+ '- `slide`: same as `tap` but allows sliding between values',
+ '- `click`: activates upon click only and allows further scrolling',
+ ]},
+ colorTextOn: {type: 'string', value: 'auto', help: 'Defines the widget\'s text color when active.'},
+
+ }, [], {}, Switch)
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.container.classList.add('layout-' + this.getProp('layout'))
+
+ if (this.getProp('layout') === 'grid') {
+ var template = this.getProp('gridTemplate') || 2
+ this.widget.style.gridTemplate = template === parseInt(template) ? `none / repeat(${template}, 1fr)` : template
+ }
+
+ this.parseValues()
+
+
+ var dragCallback = (e, touchFix)=>{
+
+ var index = 0,
+ node = e.target
+
+ if (touchFix && e.isTouch) {
+ // special traversing touch fix
+ node = document.elementFromPoint(e.clientX, e.clientY)
+ }
+
+ if (node === this.widget || !this.widget.contains(node)) return
+
+ while ((node = node.previousSibling)) {
+ if (node.nodeType != 3) {
+ index++
+ }
+ }
+
+ var value = this.values[index]
+
+ if (value !== this.value || this.value === undefined) this.setValue(value, {sync: true, send: true})
+
+ }
+
+ if (this.getProp('mode') === 'tap' || this.getProp('mode') === 'slide') {
+ this.on('draginit', dragCallback , {element: this.widget})
+ this.on('drag', (e)=>{
+ if (this.getProp('mode') === 'slide' || e.traversing) dragCallback(e, true)
+ } , {element: this.widget})
+ } else {
+ this.widget.addEventListener('click', dragCallback)
+
+ }
+
+ }
+
+ parseValues() {
+
+ super.parseValues()
+
+ for (var i = 0; i < this.values.length; i++) {
+
+ this.widget.appendChild(html`
+ ${raw(iconify(this.keys[i]))}
+ `)
+
+ }
+
+ }
+
+ setValue(v, options={}) {
+
+ var i = this.getIndex(v)
+
+
+ if (i !== -1) {
+
+ this.value = this.values[i]
+
+ DOM.each(this.widget, '.on', (el)=>{el.classList.remove('on')})
+ DOM.get(this.widget, 'value')[i].classList.add('on')
+
+ if (options.send) this.sendValue(this.value)
+ if (options.sync) this.changed(options)
+ }
+
+ }
+
+ setCssVariables() {
+
+ super.setCssVariables()
+
+ this.container.classList.toggle('padding-0', this.getProp('padding') === -1)
+
+ }
+}
+
+Switch.cssVariables = Switch.prototype.constructor.cssVariables.concat(
+ {js: 'colorTextOn', css: '--color-text-on'}
+)
+
+module.exports = Switch
diff --git a/src/client/widgets/common/canvas.js b/src/client/widgets/common/canvas.js
new file mode 100644
index 00000000..6c7194f1
--- /dev/null
+++ b/src/client/widgets/common/canvas.js
@@ -0,0 +1,181 @@
+var Widget = require('./widget'),
+ resize = require('../../events/resize'),
+ canvasQueue = require('./queue')
+
+
+class Canvas extends Widget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.canvas = DOM.get(this.container, 'canvas')[0]
+
+ this.ctx = this.canvas.getContext('2d',{
+ desynchronized: !ELECTRON_NOGPU && ENV.desyncCanvas ? true : false,
+ alpha: true
+ })
+
+ this.height = undefined
+ this.width = undefined
+ this.scaling = 1
+
+ this.clearRect = []
+
+ this.hasSize = false
+
+ this.colors = {}
+ this.cssVars = {}
+
+ this.on('resize', this.resizeHandleProxy.bind(this), {element: this.canvas})
+
+ this.ctx.arc = (x, y, r, s, e, c)=>{
+
+ this.ctx.__proto__.arc.call(this.ctx, x, y, Math.max(0,r), s, e, c)
+
+ }
+
+ }
+
+ resizeHandleProxy() {
+
+ this.resizeHandle(...arguments)
+
+ }
+
+ resizeHandle(event){
+
+ var {width, height, style} = event,
+ ratio = CANVAS_SCALING * this.scaling
+
+ this.height = height
+ this.width = width
+
+ this.canvas.setAttribute('width', width * ratio)
+ this.canvas.setAttribute('height', height * ratio)
+
+ this.clearRect = []
+
+ if (ratio != 1) {
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ this.ctx.scale(ratio, ratio)
+ }
+
+ this.cacheCanvasStyle(style)
+
+ if (!this.hasSize) {
+ this.hasSize = true
+ this.setVisibility()
+ }
+
+ this.batchDraw()
+
+ }
+
+ cacheCanvasStyle(style){
+
+ style = style || window.getComputedStyle(this.canvas)
+
+
+ for (var data of this.constructor.cssVariables) {
+
+ var val = style.getPropertyValue(data.css).trim()
+ this.cssVars[data.js] = data.toJs ? data.toJs(val) : val
+
+ }
+
+ this.fontFamily = style.getPropertyValue('font-family').trim()
+ this.textAlign = style.getPropertyValue('text-align').trim()
+ this.fontSize = parseFloat(style.getPropertyValue('font-size').trim())
+ this.fontWeight = parseFloat(style.getPropertyValue('font-weight').trim())
+
+ this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily
+ this.ctx.textBaseline = 'middle'
+ this.ctx.textAlign = this.textAlign
+
+ }
+
+ clear() {
+
+ if (!this.clearRect.length) {
+
+ this.ctx.clearRect(0, 0, this.width, this.height)
+
+ } else if (typeof this.clearRect[0] == 'object') {
+
+ for (let i in this.clearRect) {
+ this.ctx.clearRect(...this.clearRect[i])
+ }
+
+ } else {
+
+ this.ctx.clearRect(...this.clearRect)
+
+ }
+
+ }
+
+ isVisible() {
+
+ return this.hasSize && super.isVisible()
+
+ }
+
+ batchDraw() {
+
+ if (this.visible) canvasQueue.push(this)
+
+ }
+
+ draw(){
+ throw new Error('Calling unimplemented draw() method')
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+
+ case 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ case 'colorBg':
+ setTimeout(()=>{
+ this.cacheCanvasStyle()
+ this.batchDraw()
+ },10)
+ return
+ case 'css':
+ case 'lineWidth':
+ case 'padding':
+ resize.check(this.canvas, true)
+ setTimeout(()=>{
+ this.cacheCanvasStyle()
+ this.batchDraw()
+ },10)
+ return
+ }
+
+ return ret
+
+
+ }
+
+ onRemove() {
+ this.off('resize')
+ super.onRemove()
+ }
+
+}
+
+Canvas.cssVariables = Canvas.prototype.constructor.cssVariables.concat(
+ {js: 'alphaPips', css: '--alpha-pips', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
+ {js: 'alphaPipsText', css: '--alpha-pips-text', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)}
+)
+
+module.exports = Canvas
diff --git a/src/client/widgets/common/container.js b/src/client/widgets/common/container.js
new file mode 100644
index 00000000..22bc36f3
--- /dev/null
+++ b/src/client/widgets/common/container.js
@@ -0,0 +1,75 @@
+var Widget = require('./widget')
+
+var Container = (Class=Widget)=> class extends Class {
+
+ constructor(options) {
+
+ super(options)
+
+ this.on('widget-created', (e)=>{
+
+ if (e.widget.parent === this) {
+
+ var index = e.index
+ if (index !== undefined) {
+ if (!this.children[index]) {
+ this.children[index] = e.widget
+ } else {
+ this.children.splice(index, 0, e.widget)
+ }
+ } else {
+ this.children.push(e.widget)
+ }
+ }
+
+ })
+
+ this.on('widget-removed', (e)=>{
+
+ if (e.widget.parent === this) {
+ this.children.splice(this.children.indexOf(e.widget), 1)
+ }
+
+ })
+
+ }
+
+ alignChildrenProps() {
+
+ // this is needed after editor.undo to fix data shifting:
+ // say we have children [a, b, c] bound with session data [a, b, c]
+ // we delete one widget [ b, c] the data changes too: [ b, c]
+ // undo first only mutates the data: [a, b, c]
+ // so children have their data mutated too, child 'b' gets data 'a' and so on
+ // each child has to get the data corresponding to its index again.
+ // ...right ? :)
+ var tabs = this.getProp('tabs'),
+ widgets= this.getProp('widgets'),
+ type = tabs && tabs.length ? 'tabs' : widgets && widgets.length ? 'widgets' : null,
+ data = type ? this.getProp(type) : null
+
+ if (!type) return
+
+
+ for (let i in this.children) {
+ if (this.children[i] && data[i]) {
+ this.children[i].props = data[i]
+ this.children[i].cachedProps[type] = this.children[i].props[type]
+ if (this.children[i].alignChildrenProps) {
+ this.children[i].alignChildrenProps()
+ }
+ }
+ }
+
+ }
+
+ onRemove() {
+
+ super.onRemove()
+
+ }
+
+}
+
+
+module.exports = Container
diff --git a/src/client/widgets/common/osc-receiver.js b/src/client/widgets/common/osc-receiver.js
new file mode 100644
index 00000000..3f3ed4b2
--- /dev/null
+++ b/src/client/widgets/common/osc-receiver.js
@@ -0,0 +1,81 @@
+var osc = require('../../osc'),
+ {isJSON} = require('../../utils')
+
+module.exports = class OscReceiver {
+
+ constructor(options) {
+
+ var {address, value, parent, propName, usePreArgs} = options
+
+ if (typeof value === 'string' && isJSON(value)) {
+ try {
+ this.value = JSON.parseFlex(value)
+ } catch (err) {
+ this.value = value
+ }
+ } else {
+ this.value = value
+ }
+
+ this.parent = parent
+ this.propNames = [propName]
+ this.usePreArgs = usePreArgs
+ this.bindedCallback = this.callback.bind(this)
+ this.prefix = ''
+ this.setAddress(address)
+
+ }
+
+ setAddress(address) {
+
+ if (this.address !== address) {
+
+ if (this.address) osc.off(this.prefix + this.address, this.bindedCallback, this.parent)
+
+ if (address) this.address = address
+
+ if (this.address[0] !== '/') {
+ var parentAddress = this.parent.getProp('address') || this.parent.resolveProp('address', undefined, false, this)
+ if (parentAddress === 'auto') parentAddress = '/' + this.parent.getProp('id')
+ this.prefix = parentAddress
+ if (this.prefix[this.prefix.length - 1] !== '/') this.prefix += '/'
+ }
+
+ osc.on(this.prefix + this.address, this.bindedCallback, {context: this.parent})
+
+ }
+
+ }
+
+ addProp(propName){
+
+ if (!this.propNames.includes(propName)) this.propNames.push(propName)
+
+ }
+
+ callback(args) {
+
+ if (!Array.isArray(args)) args = [args]
+ var preArgs = this.usePreArgs ? (this.parent.getProp('preArgs') || []) : []
+ if (!Array.isArray(preArgs) && preArgs !== '') preArgs = [preArgs]
+ if (args.length >= preArgs.length) {
+ for (var i in preArgs) {
+ if (preArgs[i] !== args[i]) return
+ }
+ var value = args.slice(preArgs.length)
+ if (value.length < 2) value = value[0]
+ if (typeof value === 'string' && isJSON(value)) {
+ try {
+ this.value = JSON.parseFlex(value)
+ } catch (err) {
+ this.value = value
+ }
+ } else {
+ this.value = value
+ }
+ this.parent.updateProps(this.propNames)
+ }
+
+ }
+
+}
diff --git a/src/client/widgets/common/queue.js b/src/client/widgets/common/queue.js
new file mode 100644
index 00000000..9b0ba092
--- /dev/null
+++ b/src/client/widgets/common/queue.js
@@ -0,0 +1,66 @@
+var EventEmitter = require('../../events/event-emitter')
+
+class CanvasQueue extends EventEmitter{
+
+ constructor() {
+
+ super()
+
+ this.queue = {}
+ this.flushed = 0
+ this.running = false
+ this.frameLength = 1000 / CANVAS_FRAMERATE
+ this.lastFrame = 0
+ this.bindedLoop = this.loop.bind(this)
+
+ }
+
+ push(widget) {
+
+ this.queue[widget.hash] = widget
+ this.flushed = 0
+ if (!this.running) this.startLoop()
+
+ }
+
+ startLoop() {
+
+ this.running = true
+ this.flushed = 0
+ requestAnimationFrame(this.bindedLoop)
+
+ }
+
+ flush() {
+
+ for (var h in this.queue) {
+ this.queue[h].draw()
+ }
+
+ this.queue = {}
+ this.flushed++
+
+ }
+
+ loop(timestamp) {
+
+ if (this.flushed >= 10) {
+ this.running = false
+ return
+ }
+
+ requestAnimationFrame(this.bindedLoop)
+
+ var delta = timestamp - this.lastFrame
+
+ if (delta > this.frameLength) {
+ this.lastFrame = timestamp - (delta % this.frameLength)
+ this.trigger('frame', {timestamp})
+ this.flush()
+ }
+
+ }
+
+}
+
+module.exports = new CanvasQueue()
diff --git a/src/client/widgets/common/widget.js b/src/client/widgets/common/widget.js
new file mode 100644
index 00000000..f260505b
--- /dev/null
+++ b/src/client/widgets/common/widget.js
@@ -0,0 +1,1081 @@
+var EventEmitter = require('../../events/event-emitter'),
+ osc = require('../../osc'),
+ nanoid = require('nanoid/generate'),
+ widgetManager = require('../../managers/widgets'),
+ {urlParser} = require('../utils'),
+ Vm = require('../vm'),
+ vm = new Vm(),
+ scopeCss = require('scope-css'),
+ resize = require('../../events/resize'),
+ OscReceiver = require('./osc-receiver'),
+ {deepCopy, deepEqual, isJSON} = require('../../utils'),
+ html = require('nanohtml'),
+ updateWidget = ()=>{},
+ Script
+
+
+var oscReceiverState = {}
+
+var OSCProps = [
+ 'decimals',
+ 'address',
+ 'preArgs',
+ 'typeTags',
+ 'target',
+ 'bypass'
+]
+
+var dummyDOM
+
+DOM.ready(()=>{
+ dummyDOM = html`
`
+})
+
+setTimeout(()=>{
+ updateWidget = require('../../editor/data-workers').updateWidget
+})
+
+class Widget extends EventEmitter {
+
+ static description() {
+
+ return ''
+
+ }
+
+ static defaults(insert={}, except=[], push={}, Class=Widget) {
+
+ var defaults = {
+
+ _widget: 'widget',
+
+ type: {type: 'string', value: 'auto', help: 'Widget type'},
+ id: {type: 'string', value: 'auto', help: 'Widgets sharing the same `id` will act as clones and update each other\'s value(s) without sending extra osc messages.' },
+ visible: {type: 'boolean', value: true, help: 'Set to `false` to hide the widget.'},
+ interaction: {type: 'boolean', value: true, help: 'Set to `false` to disable pointer interactions.'},
+
+ _geometry: 'geometry',
+
+ left: {type: 'number|string', value: 'auto', help: [
+ 'When both top and left are set to auto, the widget is positioned according to the normal flow of the page (from left to right, by order of creation).',
+ 'Otherwise, the widget will be absolutely positioned'
+ ]},
+ top: {type: 'number|percentage', value: 'auto', help: [
+ 'When both top and left are set to auto, the widget is positioned according to the normal flow of the page (from left to right, by order of creation).',
+ 'Otherwise, the widget will be absolutely positioned'
+ ]},
+ width: {type: 'number|percentage', value: 'auto', help: 'Widget width'},
+ height: {type: 'number|percentage', value: 'auto', help: 'Widget height'},
+ expand: {type: 'boolean|number', value: 'false', help: 'If parent\'s layout is `vertical` or `horizontal`, set this to `true` to stretch the widget to use available space automatically.'},
+
+ _style: 'style',
+
+
+ colorBg: {type: 'string', value: 'auto', help: 'Panel background color. Set to "auto" to inherit from parent widget.'},
+ colorText: {type: 'string', value: 'auto', help: 'Text color. Set to "auto" to inherit from parent widget.'},
+ colorWidget: {type: 'string', value: 'auto', help: 'Widget\'s default accent color. Set to "auto" to inherit from parent widget.'},
+ colorStroke: {type: 'string', value: 'auto', help: 'Stroke color. Set to "auto" to use `colorWidget`.'},
+ colorFill: {type: 'string', value: 'auto', help: 'Fill color. Set to "auto" to use `colorWidget`.'},
+ alphaStroke: {type: 'number', value: 'auto', help: 'Stroke color opacity.'},
+ alphaFillOff: {type: 'number', value: 'auto', help: 'Fill color opacity (off).'},
+ alphaFillOn: {type: 'number', value: 'auto', help: 'Fill color opacity (on).'},
+
+ lineWidth: {type: 'number', value: 'auto', help: 'Stroke width.'},
+ padding: {type: 'number', value: 'auto', help: 'Inner spacing.'},
+
+
+
+ css: {type: 'string', value: '', help: [
+ 'CSS rules. See documentation .',
+ 'Available css variables:',
+ ...Class.cssVariables.map(x=>'- `' + x.css + '`: `' + x.js + '`')
+ ]},
+
+ _value: 'value',
+
+ value: {type: '*', value: '', help: 'Define the widget\'s value depending on other widget\'s values / properties using the advanced property syntax'},
+ default: {type: '*', value: '', help: 'If set, the widget will be initialized with this value when the session is loaded.'},
+ linkId: {type: 'string|array', value: '', help: [
+ 'Widgets sharing the same `linkId` update each other\'s value(s) AND send their respective osc messages.',
+ 'When prefixed with >>, the `linkId` will make the widget act as a master (sending but not receiving)',
+ 'When prefixed with <<, the `linkId` will make the widget act as a slave (receiving but not sending)'
+ ]},
+ script: {type: 'script', value: '', help: 'Script executed whenever the widget\'s value updates. See documentation .'},
+
+ _osc: 'osc',
+
+ address: {type: 'string', value: 'auto', help: [
+ 'OSC address for sending / receiving messages, it must start with a slash (`/`)',
+ 'By default ("auto"), the widget\'s id is used: `/widget_id`',
+ ]},
+ preArgs: {type: '*|array', value: '', help: [
+ 'A value or array of values that will be prepended to the OSC messages.',
+ ]},
+ typeTags: {type: 'string', value: '', help: [
+ 'Defines the osc argument types, one letter per argument (including preArgs)',
+ '- If empty, the types are infered automatically from the values (with numbers casted to floats by default)',
+ '- If there are more arguments than type letters, the last type is used for the extra arguments',
+ 'See http://opensoundcontrol.org/spec-1_0 for existing typetags'
+ ]},
+ decimals: {type: 'integer', value: 2, help: [
+ 'Defines the number of decimals to send.',
+ ]},
+ target: {type: 'string|array|null', value: '', help: [
+ 'This defines the targets of the widget\'s OSC messages',
+ '- A `string` or `array` of strings formatted as follow: `ip:port` or `["ip:port"]`',
+ '- If midi is enabled, targets can be `midi:device_name`',
+ '- If no target is set, messages can still be sent if the server has default targets',
+ ]},
+ ignoreDefaults: {type: 'boolean', value: false, help: 'Set to `true` to ignore the server\'s default targets'},
+ bypass: {type: 'boolean', value: false, help: 'Set to `true` to prevent the widget from sending any osc message'}
+
+ }
+
+ // okay that's bad, but keys happen to be ordered anyway...
+
+ var alterDefaults = {}
+
+ for (var k in defaults) {
+ if (k === '_value') {
+ for (var l in insert) {
+ alterDefaults[l] = insert[l]
+ }
+ }
+ if (except.indexOf(k) < 0) alterDefaults[k] = defaults[k]
+ }
+
+ for (var m in push) {
+ if (!alterDefaults[m]) alterDefaults[m] = []
+ if (typeof push[m] === 'string') alterDefaults[m] = push[m]
+ else Object.assign(alterDefaults[m], push[m])
+ }
+
+ alterDefaults._props = function() {
+ var props = {}
+ for (var k in this) {
+ if (k[0] !== '_') {
+ props[k] = this[k].value
+ }
+ }
+ return props
+ }
+
+
+ return alterDefaults
+
+ }
+
+ constructor(options={}) {
+
+ super()
+
+ this.widget = options.html
+ this.props = options.props
+ this.errors = {}
+ this.parent = options.parent
+ this.parentNode = options.parentNode
+ this.hash = options.hash || nanoid('abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10)
+ this.children = []
+ this.reCreateOptions = options.reCreateOptions
+ this.removed = false
+ this.mounted = false
+ this.visible = true
+
+ this.parsers = {}
+ this.parsersLocalScope = options.locals || {}
+
+ this.createPropsCache()
+
+ if (this.getProp('id') == 'root' && this.parent !== widgetManager) {
+ this.props.id = '_root'
+ this.cachedProps.id = '_root'
+ }
+
+ if (this.getProp('type') == 'root' && this.parent !== widgetManager) {
+ this.props.type = 'panel'
+ this.cachedProps.type = 'panel'
+ }
+
+
+
+ // cache decimals
+ if (this.props.decimals !== undefined) {
+ this.decimals = Math.min(20, Math.max(this.getProp('decimals'), 0))
+ }
+
+ Script = Script || require('../scripts/script')
+ if (this.getProp('script') && !(this instanceof Script)) {
+ this.script = new Script({props:{
+ id: this.getProp('id') + '/script',
+ script: this.getProp('script'),
+ event: 'value'
+ }, builtIn: true, parent: this})
+ this.on('change', (e)=>{
+ if (e.widget === this && this.mounted && !e.options.fromEdit) this.script.setValue(this.value, {...e.options, id: e.options.id || e.id})
+ })
+
+ }
+
+ this.container = html`
+
+ `
+
+ if (this.widget) this.container.appendChild(this.widget)
+ this.container._widget_instance = this
+
+
+ this.container.classList.toggle('no-interaction', !this.getProp('interaction'))
+
+ this.setContainerStyles()
+ this.setCssVariables()
+ this.setVisibility()
+
+ }
+
+ contains(widget) {
+
+ if (this.children.indexOf(widget) > 0) return true
+
+ var parent = widget.parent
+ while (parent && parent !== widgetManager) {
+ if (parent === this) return true
+ parent = parent.parent
+ }
+ return false
+
+ }
+
+ getAllChildren() {
+
+ var children = []
+ for (var i = 0; i < this.children.length; i++) {
+ if (!this.children[i]) continue
+ children.push(this.children[i])
+ children = children.concat(this.children[i].getAllChildren())
+ }
+ return children
+
+
+ }
+
+ created(index) {
+
+ this.trigger('widget-created', {
+ id: this.getProp('id'),
+ widget: this,
+ options: this.reCreateOptions,
+ index: index
+ })
+
+ }
+
+ changed(options) {
+
+ this.trigger('change', {
+ widget: this,
+ options: options,
+ id: this.getProp('id'),
+ linkId: this.getProp('linkId')
+ })
+
+ }
+
+ sendValue(overrides, options={}) {
+
+ if (this.selfLinkedOSCProps) {
+ this.updateProps(this.selfLinkedOSCProps, this)
+ }
+
+ if (this.getProp('bypass') && !options.force) return
+
+ var data = {
+ h: this.hash,
+ v: this.getValue(true),
+ }
+
+ if (this.getProp('ignoreDefaults')) data.i = 1
+
+ if (overrides) {
+ for (var k in overrides) {
+ data[k] = overrides[k]
+ }
+ }
+
+ if (options.syncOnly) {
+
+ osc.sync(data)
+
+ } else {
+
+ osc.send(data)
+
+ }
+
+ }
+
+ setValue() {}
+
+ getValue(withdecimals) {
+
+ return deepCopy(this.value, withdecimals ? this.decimals : undefined)
+
+ }
+
+ checkLinkedProps(propNames) {
+
+ // Dynamic props cache check
+ var linkedProps = []
+
+ Object.values(this.nestedLinkedProps).forEach(l => linkedProps = linkedProps.concat(l))
+ Object.values(this.linkedProps).forEach(l => linkedProps = linkedProps.concat(l))
+ Object.values(this.linkedPropsValue).forEach(l => linkedProps = linkedProps.concat(l))
+ Object.values(this.oscReceivers).forEach(r => linkedProps = linkedProps.concat(r.propNames))
+
+ if (
+ // if prop/osc listeners have changed (@{} / OSC{})
+ // refresh the widget's props cache and update linked props bindings
+ propNames.map(x => this.props[x]).some(x => typeof x === 'string' && x.match(/OSC\{|@\{/))
+ || propNames.some(n => linkedProps.includes(n))
+ ) {
+ this.createPropsCache()
+ }
+
+ }
+
+ createPropsCache() {
+
+ // @{props} links lists
+ this.linkedProps = {}
+ this.nestedLinkedProps = {}
+ this.linkedPropsValue = {}
+
+ // OSC{/path} receivers
+ if (this.oscReceivers) {
+ this.removeOscReceivers()
+ }
+ this.oscReceivers = {}
+
+ // Cache resolved props
+ this.cachedProps = {}
+
+ for (var k in this.props) {
+ if (k != 'widgets' && k != 'tabs') {
+ this.cachedProps[k] = this.resolveProp(k, undefined, true)
+ } else {
+ this.cachedProps[k] = this.props[k]
+ }
+ }
+
+ this.createLinkedPropsBindings()
+
+ }
+
+ createLinkedPropsBindings() {
+
+ if (!this.linkedCreatedCallback && Object.keys(this.linkedProps).length) {
+
+ this.linkedCreatedCallback = (e)=>{
+ this.onLinkedPropsChanged(e, 'widget-created')
+ }
+
+ this.linkedPropChangedCallback = (e)=>{
+ this.onLinkedPropsChanged(e, 'prop-changed')
+ }
+
+ widgetManager.on('widget-created', this.linkedCreatedCallback, {context: this})
+ widgetManager.on('prop-changed', this.linkedPropChangedCallback, {context: this})
+
+ } else if (this.linkedCreatedCallback && !Object.keys(this.linkedProps).length) {
+
+ widgetManager.off('widget-created', this.linkedCreatedCallback)
+ widgetManager.off('prop-changed', this.linkedPropChangedCallback)
+ delete this.linkedCreatedCallback
+ delete this.linkedPropChangedCallback
+
+ }
+
+ if (!this.linkedValueChangedCallback && Object.keys(this.linkedPropsValue).length) {
+
+ this.linkedValueChangedCallback = (e)=>{
+ this.onLinkedPropsChanged(e, 'change')
+ }
+
+ widgetManager.on('change', this.linkedValueChangedCallback, {context: this})
+
+ } else if (this.linkedPropsValueCallback && !Object.keys(this.linkedPropsValue).length) {
+
+ widgetManager.off('change', this.linkedValueChangedCallback)
+ delete this.linkedValueChangedCallback
+
+ }
+
+ var selfLinkedOSCProps = (this.linkedPropsValue['this'] || []).filter(i=>OSCProps.indexOf(i) > -1)
+ this.selfLinkedOSCProps = selfLinkedOSCProps.length ? selfLinkedOSCProps : false
+
+ }
+
+ onLinkedPropsChanged(e, type) {
+
+ var {id, widget, options} = e,
+ changedProps = type === 'prop-changed' ? e.props : type === 'change' ? ['value'] : undefined,
+ linkedProps = type === 'change' ? this.linkedPropsValue : this.linkedProps
+
+ if (widget === this.parent) {
+ if (type === 'widget-created') return
+ id = 'parent'
+ }
+
+ if (widget === this) id = 'this'
+
+ if (this.nestedLinkedProps[id]) {
+ this.updateLinkedPropsWithNesting(id)
+ }
+
+ if (linkedProps[id]) {
+ this.updateProps(linkedProps[id], widget, options, changedProps)
+ }
+
+ }
+
+ removeOscReceivers() {
+
+ osc.off(undefined, undefined, this)
+ for (var i in this.oscReceivers) {
+ oscReceiverState[i] = this.oscReceivers[i].value
+ }
+ this.oscReceivers = {}
+
+ }
+
+ updateLinkedPropsWithNesting(i) {
+
+ for (var prop of this.nestedLinkedProps[i]) {
+
+ // 1. remove all linked props found in properties bound to the nested link
+ for (var linksStores of [this.linkedPropsValue, this.linkedProps]) {
+ for (let id in linksStores) {
+ if (linksStores[id].includes(prop)) {
+ linksStores[id].splice(linksStores[id].indexOf(prop), 1)
+ if (!linksStores[id].length) delete linksStores[id]
+ }
+ }
+ }
+
+
+ // 2. resolve these props again and recreate links (3rd arg to true)
+ this.resolveProp(prop, undefined, true, this)
+
+ }
+
+
+ }
+
+ resolveProp(propName, propValue, storeLinks=true, originalWidget, originalPropName, context) {
+
+ propValue = propValue !== undefined ? propValue : deepCopy(this.props[propName])
+ originalWidget = originalWidget || this
+ originalPropName = originalPropName || propName
+
+ var variables = {},
+ defaultScope = this.constructor.parsersContexts[propName] || {},
+ jsScope = context || {},
+ varnumber = 999
+
+ if (typeof propValue == 'string') {
+
+ propValue = propValue.replace(/@\{[^{}]*((@\{[^{}]*\}|[^{}]*)*)\}/g, (m, nested)=>{
+ // pretty regexp:
+ // @\{
+ // [^{}]*
+ // ((
+ // @\{
+ // [^{}]*
+ // \}
+ // |
+ // [^{}]*
+ // )*)
+ //
+ // \}
+
+ if (nested) {
+ m = m.replace(nested, this.resolveProp(propName, nested, storeLinks ? 'nested' : false, this))
+ }
+
+ let id = m.substr(2, m.length - 3).split('.'),
+ k, subk
+
+ if (id.length > 1) {
+
+ k = id.pop()
+ subk = undefined
+
+ if (id.length > 1) {
+ subk = k
+ k = id.pop()
+ }
+
+ id = id.join('.')
+
+ } else {
+
+ id = id[0]
+ k = 'value'
+
+ }
+
+ var widgets = id == 'parent' && this.parent ?
+ [this.parent] : id == 'this' ? [this] :
+ widgetManager.getWidgetById(id)
+
+ if (!widgets.length) {
+ var parent = this.parent
+ while (parent && parent != widgetManager) {
+ if (parent.getProp('id') == id) {
+ widgets.push(parent)
+ break
+ }
+ parent = parent.parent
+ }
+ }
+
+
+ // ignore clone wrapper in @parent stack (https://github.com/jean-emmanuel/open-stage-control/issues/379)
+ if (widgets[0] === this.parent && this.parent !== widgetManager && this.parent.getProp('type') === 'clone') widgets = [this.parent.parent]
+
+ if (storeLinks) {
+
+ if (k == 'value') {
+
+ if (!this.linkedPropsValue[id]) this.linkedPropsValue[id] = []
+ if (this.linkedPropsValue[id].indexOf(propName) == -1) this.linkedPropsValue[id].push(propName)
+
+ } else {
+
+ if (!this.linkedProps[id]) this.linkedProps[id] = []
+ if (this.linkedProps[id].indexOf(propName) == -1) this.linkedProps[id].push(propName)
+
+ }
+
+ if (storeLinks === 'nested') {
+ if (!this.nestedLinkedProps[id]) this.nestedLinkedProps[id] = []
+ if (this.nestedLinkedProps[id].indexOf(propName) == -1) this.nestedLinkedProps[id].push(propName)
+ }
+
+ }
+
+ for (var i in widgets) {
+
+ if (widgets[i] === widgetManager) continue
+
+ if (widgets[i].props[k] !== undefined || k === 'value') {
+
+ if (k !== 'value' && originalPropName === k && widgets[i] === originalWidget) {
+ return 'ERR_CIRCULAR_REF'
+ }
+
+ var r = k == 'value' ?
+ widgets[i].getValue(true) :
+ widgets[i].resolveProp(k, undefined, storeLinks, originalWidget, originalPropName)
+
+ if (subk !== undefined && r !== undefined) r = r[subk]
+
+ var varname = 'VAR_' + varnumber
+ varnumber--
+
+ variables[varname] = r
+ jsScope[varname] = r
+
+ return varname
+
+ }
+
+ }
+
+ })
+
+ propValue = propValue.replace(/OSC\{([^}]+)\}/g, (m, args)=>{
+
+ let [address, value, usePreArgs] = args.split(',')
+ .map(x=>x.trim())
+ .map(x=>x.replace(/VAR_[0-9]+/g, (m)=>{
+ return typeof variables[m] === 'string' ? variables[m] : JSON.stringify(variables[m])
+ }))
+
+ if (!this.oscReceivers[args]) {
+ this.oscReceivers[args] = new OscReceiver({
+ address: address,
+ value: value,
+ parent: this,
+ propName: propName,
+ usePreArgs: usePreArgs === 'false' ? false : true
+ })
+ if (oscReceiverState[args]) {
+ this.oscReceivers[args].value = oscReceiverState[args]
+ delete oscReceiverState[args]
+ }
+ } else {
+ this.oscReceivers[args].setAddress(address)
+ this.oscReceivers[args].addProp(propName)
+ this.oscReceivers[args].usePreArgs = usePreArgs === 'false' ? false : true
+ }
+
+ var r = this.oscReceivers[args].value
+
+ var varname = 'VAR_' + varnumber
+ varnumber--
+
+ variables[varname] = r
+ jsScope[varname] = r
+
+ return varname
+ })
+
+ try {
+ propValue = propValue.replace(/JS\{\{([\s\S]*)\}\}/g, (m, code)=>{
+
+ if (!this.parsers[code]) this.parsers[code] = vm.compile(code, defaultScope)
+
+ let r = this.parsers[code](jsScope, this.parsersLocalScope)
+
+ if (r === undefined) r = ''
+
+ return typeof r !== 'string' ? JSON.stringify(r) : r
+
+ })
+ } catch (err) {
+ let stackline = err.stack ? (err.stack.match(/>:([0-9]+):[0-9]+/) || '') : '',
+ line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - 2) : ''
+ console.log((this.getProp('id') || this.props.id) + '.' + propName + ': JS{{}} error:\n' + err + line)
+ }
+
+ try {
+ propValue = propValue.replace(/#\{(?:[^{}]|\{[^{}]*\})*\}/g, (m)=>{
+ // one bracket nesting allowed, if we need two: #\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}
+
+ var code = m.substr(2, m.length - 3).trim()
+
+ if (!this.parsers[code]) this.parsers[code] = vm.compile('return ' + code, defaultScope)
+
+ let r = this.parsers[code](jsScope, this.parsersLocalScope)
+
+ if (r === undefined) r = ''
+
+ return typeof r !== 'string' ? JSON.stringify(r) : r
+
+ })
+ } catch (err) {
+ let stackline = err.stack ? (err.stack.match(/>:([0-9]+):[0-9]+/) || '') : '',
+ line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - 2) : ''
+ console.log((this.getProp('id') || this.props.id) + '.' + propName + ': #{} error:\n' + err + line)
+ }
+
+ for (let k in variables) {
+ var v = typeof variables[k] === 'string' ? variables[k] : JSON.stringify(variables[k])
+ propValue = propValue.replace(new RegExp(k, 'g'), v)
+ }
+
+ if (isJSON(propValue)) {
+ try {
+ propValue = JSON.parse(propValue)
+ } catch (err) {}
+ }
+
+ } else if (propValue != null && typeof propValue == 'object') {
+ for (let k in propValue) {
+ propValue[k] = this.resolveProp(propName, propValue[k], storeLinks, originalWidget, originalPropName, context)
+ }
+ }
+
+ return propValue
+
+
+ }
+
+ getProp(propName) {
+ return this.cachedProps[propName]
+ }
+
+
+ isDynamicProp(propName) {
+
+ return this.constructor.dynamicProps.indexOf(propName) !== -1
+
+ }
+
+ updateProps(propNames, widget, options, updatedProps = []) {
+
+ if (propNames.includes('value')) {
+ propNames.splice(propNames.indexOf('value'), 1)
+ propNames.push('value')
+ }
+
+ if (widget && options) options.id = widget.getProp('id')
+
+ var reCreate = false,
+ changedProps = []
+
+ for (var propName of propNames) {
+
+ if (widget === this && updatedProps.includes(propName)) continue
+
+ let propValue = this.resolveProp(propName, undefined, false),
+ oldPropValue = this.getProp(propName)
+
+ if (!deepEqual(oldPropValue, propValue)) {
+
+ if (!this.isDynamicProp(propName)) {
+
+ if ((!widget || !this.contains(widget)) && !(widget === this && updatedProps.length === 1 && updatedProps[0] === 'value')) {
+ reCreate = true
+ break
+ }
+
+ } else {
+
+ this.cachedProps[propName] = propValue
+ changedProps.push({propName, oldPropValue})
+
+ }
+
+
+ }
+ }
+
+ if (reCreate) {
+
+ return this.reCreateWidget({reCreateOptions: options})
+
+ }
+
+ if (options && options.fromEditor) {
+ this.checkLinkedProps(propNames)
+ }
+
+ if (changedProps.length) {
+
+ for (var i in changedProps) {
+ this.onPropChanged(changedProps[i].propName, options, changedProps[i].oldPropValue)
+ }
+
+ widgetManager.trigger('prop-changed', {
+ id: this.getProp('id'),
+ props: changedProps,
+ widget: this,
+ options: options
+ })
+
+ }
+
+ }
+
+ onPropChanged(propName, options={}, oldPropValue) {
+
+ switch(propName) {
+
+ case 'value':
+ this.setValue(this.getProp('value'), {sync: true, send: options.send, id: options.id})
+ return
+
+ case 'top':
+ case 'left':
+ this.setContainerStyles(['geometry'])
+ return
+
+ case 'height':
+ case 'width':
+ case 'expand': {
+ this.setContainerStyles(['geometry'])
+ let container = this.parent !== widgetManager && this.parent.getProp('layout') !== 'default' ? this.parent.container : this.container
+ resize.check(container)
+ return
+ }
+
+ case 'visible': {
+ this.setVisibility()
+ let container = this.parent !== widgetManager && this.parent.getProp('layout') !== 'default' ? this.parent.container : this.container
+ resize.check(container)
+ return
+ }
+
+ case 'interaction':
+ this.container.classList.toggle('no-interaction', !this.getProp('interaction'))
+ return
+
+ case 'css': {
+ this.setContainerStyles(['css'])
+ var re = /width|height|display|margin|padding|flex/
+ if (re.test(oldPropValue) || re.test(this.getProp('css'))) {
+ let container = this.parent !== widgetManager && this.parent.getProp('layout') !== 'default' ? this.parent.container : this.container
+ resize.check(container)
+ }
+ return
+ }
+
+ case 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ case 'lineWidth':
+ case 'padding':
+ this.setCssVariables()
+ return
+
+ case 'decimals':
+ this.decimals = Math.min(20, Math.max(this.getProp('decimals'), 0))
+ return
+
+ case 'address':
+ case 'preArgs':
+ case 'typeTags':
+ case 'target':
+ if (propName === 'address') {
+ for (var k in this.oscReceivers) {
+ var receiver = this.oscReceivers[k]
+ if (receiver.prefix !== '') {
+ receiver.setAddress()
+ }
+ }
+ }
+ var data = {},
+ oldData = {
+ preArgs: propName == 'preArgs' ? oldPropValue : this.getProp('preArgs'),
+ address: propName == 'address' ? oldPropValue : this.getProp('address')
+ }
+ data[propName] = this.getProp(propName)
+
+ if (data.address === 'auto') data.address = '/' + this.getProp('id')
+ if (oldData.address === 'auto') oldData.address = '/' + this.getProp('id')
+
+ widgetManager.registerWidget(this, data, oldData)
+ return
+
+ }
+
+ }
+
+ setContainerStyles(styles = ['geometry', 'css', 'visibility']) {
+
+ if (styles.includes('geometry')) {
+
+ // geometry
+ var absolutePos = false
+ for (let d of ['width', 'height', 'top', 'left']) {
+ let val = this.getProp(d),
+ geometry
+
+ if (val !== undefined) {
+ if (parseFloat(val) < 0) val = 0
+ geometry = parseFloat(val) == val ? parseFloat(val)+'rem' : val
+ }
+
+ if (geometry) {
+ if (geometry === 'auto') geometry = ''
+ this.container.style[d] = geometry
+ if (d === 'width') this.container.style.minWidth = geometry
+ if (d === 'height') this.container.style.minHeight = geometry
+ absolutePos = absolutePos || geometry && (d === 'top' || d === 'left')
+
+ }
+ }
+ this.container.classList.toggle('absolute-position', absolutePos)
+ this.container.classList.toggle('flex-expand', this.getProp('expand'))
+
+
+ }
+
+ if (styles.includes('css')) {
+
+ // css
+ var css = String(this.getProp('css')),
+ extraCssClasses = []
+
+ // extra css "class" property
+ css = css.replace(/^[^\S\n]*class[^\S\n]*:[^\S\n]*([^;\n\s]+);?/igm, (m, c)=>{
+ if (c === 'widget' || c.includes('-container')) return m
+ extraCssClasses.push(c.replace(/"'/g,''))
+ return ''
+ })
+
+
+ // escpape windows absolute file paths
+ css = css.replace(/url\(([^)]*)\)/g, (m, url)=>{
+ var parser = urlParser(url)
+ if (!parser.protocol.match(/http|data/)) m = m.replace(':', '_:_')
+ m = m.replace(/\\/g, '\\\\')
+ return m
+ })
+
+
+ var prefix = '#' + this.hash,
+ scopedCss = scopeCss(css, prefix),
+ unScopedCss = ''
+
+
+ try {
+
+ dummyDOM.style = css
+ unScopedCss = dummyDOM.getAttribute('style') || ''
+
+ } catch(err) {
+
+ // fallback for browser that don't allow assigning "style" property
+ css
+ .replace(/\{[^}]*\}/g, '')
+ .replace(/^[^@#.]*:.*/gm, (m)=>{
+ unScopedCss += m[m.length - 1] === ';' ? m : m + ';'
+ })
+
+ }
+
+
+
+ if (scopedCss.indexOf('@keyframes') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s+([0-9]+%|to|from)', 'g'), ' $1')
+ if (scopedCss.indexOf('&') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s&', 'g'), prefix)
+
+ var style = html``,
+ oldStyle = DOM.get(this.container, '> style')[0]
+
+ if (oldStyle) {
+ this.container.replaceChild(style, oldStyle)
+ } else if (scopedCss.length || unScopedCss.length){
+ this.container.insertBefore(style, this.container.childNodes[0] || null)
+ }
+
+
+ // apply extra css classes
+
+ if (this.extraCssClasses && this.extraCssClasses.length) {
+ this.container.classList.remove(...this.extraCssClasses)
+ this.extraCssClasses = []
+ }
+
+ if (extraCssClasses.length) {
+ this.container.classList.add(...extraCssClasses)
+ this.extraCssClasses = extraCssClasses
+ }
+
+
+ // store transform matrix if any
+ // if (css.includes('transform')) {
+ // setTimeout(()=>{
+ // var style = window.getComputedStyle(this.container)
+ // this.cssTransform = style.transform || 'none'
+ // this.cssTransformOrigin = style.transformOrigin
+ // })
+ // } else {
+ // this.cssTransform = 'none'
+ // }
+
+
+ }
+
+ return style
+
+
+ }
+
+ setCssVariables() {
+
+
+ for (var data of this.constructor.cssVariables) {
+
+ var val = this.getProp(data.js)
+ this.container.style.setProperty(data.css, val !== undefined && val !== 'auto' ? data.toCss ? data.toCss(val) : val : '')
+
+ }
+
+ }
+
+ isVisible() {
+
+ return this.getProp('visible') && this.parent.isVisible()
+
+ }
+
+ setVisibility() {
+
+
+ var visible = this.isVisible()
+ if (visible !== this.visible) {
+ this.visible = visible
+ this.container.style.display = this.getProp('visible') ? '' : 'none'
+
+ for (var c of this.children) {
+ if (c) c.setVisibility()
+ }
+
+ }
+
+ }
+
+ reCreateWidget(options={}){
+
+ if (!this.removed) return updateWidget(this, options)
+
+ }
+
+ onRemove(){
+
+ if (this.getProp('script') && !(this instanceof Script)) {
+ this.script.onRemove()
+ }
+
+ this.removed = true
+ widgetManager.off(undefined, undefined, this)
+ this.removeOscReceivers()
+
+ }
+
+}
+
+Widget.parsersContexts = {}
+
+Widget.cssVariables = [
+ {js: 'colorBg', css: '--color-background'},
+ {js: 'colorWidget', css: '--color-widget'},
+ {js: 'colorFill', css: '--color-fill'},
+ {js: 'colorStroke', css: '--color-stroke'},
+ {js: 'colorText', css: '--color-text'},
+ {js: 'padding', css: '--widget-padding', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE},
+ {js: 'lineWidth', css: '--line-width', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE},
+ {js: 'alphaFillOn', css: '--alpha-fill-on', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
+ {js: 'alphaFillOff', css: '--alpha-fill-off', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
+ {js: 'alphaStroke', css: '--alpha-stroke', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
+]
+
+Widget.dynamicProps = [
+ 'visible',
+ 'interaction',
+
+ 'top',
+ 'left',
+ 'height',
+ 'width',
+ 'expand',
+
+
+ 'colorText',
+ 'colorWidget',
+ 'colorFill',
+ 'colorStroke',
+ 'alphaStroke',
+ 'alphaFillOff',
+ 'alphaFillOn',
+ 'padding',
+ 'lineWidth',
+ 'css',
+
+ 'value',
+
+ 'decimals',
+ 'address',
+ 'preArgs',
+ 'typeTags',
+ 'target',
+ 'bypass'
+]
+
+module.exports = Widget
diff --git a/src/client/widgets/containers/clone.js b/src/client/widgets/containers/clone.js
new file mode 100644
index 00000000..7a00331a
--- /dev/null
+++ b/src/client/widgets/containers/clone.js
@@ -0,0 +1,325 @@
+var Container = require('../common/container'),
+ widgetManager = require('../../managers/widgets'),
+ resize = require('../../events/resize'),
+ parser = require('../../parser'),
+ {deepCopy, deepEqual} = require('../../utils'),
+ {diff, diffToWidget} = require('../../editor/diff'),
+ html = require('nanohtml')
+
+var excludedCloneClasses = ['widget', 'absolute-position', 'not-editable', 'editing', 'flex-expand', 'no-interaction']
+
+class Clone extends Container() {
+
+ static description() {
+
+ return 'Widget replication with overridable properties.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'clone',
+
+ widgetId: {type: 'string', value: '', help: '`id` of the widget to clone'},
+ props: {type: 'object', value: {}, help: 'Cloned widget\'s properties to override'},
+
+ }, [
+ 'colorBg', 'colorText', 'colorWidget', 'colorFill', 'colorStroke', 'alphaStroke', 'alphaFillOff', 'alphaFillOn', 'padding', 'lineWidth',
+ 'label', 'color',
+ '_value', 'default', 'value', 'script', 'linkId',
+ '_osc', 'decimals', 'address', 'preArgs', 'typeTags', 'target', 'ignoreDefaults', 'bypass'
+ ])
+
+ }
+
+ constructor(options) {
+
+ options.props.label = ''
+ options.props.variables = '@{parent.variables}'
+
+ super({...options, html: html`
`})
+
+ this.cloneLock = false
+ this.cloneTarget = null
+ this.cloneClass = []
+
+ this.modalBreakout = 0
+
+ this.container.classList.add('empty')
+
+ this.bindTarget(this.getCloneTarget())
+ if (this.cloneTarget) this.createClone(true)
+
+ // global listener to catch cloneTarget's creation if no target is locked
+ widgetManager.on('widget-created', (e)=>{
+
+ if (this.cloneTarget) return
+
+ var {id, widget} = e
+
+ if (id === this.getProp('widgetId') && this.isValidCloneTarget(widget)) {
+
+ var clone = this.children[0]
+
+ this.unbindTarget()
+
+ if (!clone) {
+
+ this.updateContainer(false)
+ this.bindTarget(widget)
+ this.createClone()
+
+ } else {
+
+ this.bindTarget(widget)
+ this.updateClone()
+
+ }
+
+ }
+
+ }, {context: this})
+
+ widgetManager.on('prop-changed', (e)=>{
+
+ if (!this.cloneTarget) return
+
+ if (e.widget === this.cloneTarget || this.cloneTarget.contains(e.widget)) {
+
+ this.updateClone(e.options)
+
+ }
+
+ }, {context: this})
+
+ this.on('widget-created', (e)=>{
+
+ if (e.widget !== this) {
+ e.widget.container.classList.add('not-editable')
+ }
+
+ })
+
+ }
+
+ getCloneTarget() {
+
+ // attempt to acquire a cloneTarget if 'widget-created' event has not been catched
+ // (the target might have been created before the clone itself)
+
+ var widgets = widgetManager.getWidgetById(this.getProp('widgetId'))
+ .filter(el=>this.isValidCloneTarget(el))
+
+ if (widgets.length === 0) return null
+ if (widgets.length === 1) {
+ return widgets[0]
+ }
+
+ // when duplicating clones pointing to an object with a static id,
+ // each clone will recreate an object with the same id internally
+ // we try to get the original one if there is more than 2 clone pointing to the same id (avoiding cloning the clone)
+
+ function isCreatedByAClone(wi){
+ var parent = wi.parent
+ return parent && parent.getProp('type') === 'clone'
+ }
+
+ var target = widgets[0]
+ for (var w of widgets) {
+ if (!isCreatedByAClone(w)) {
+ target = w
+ break
+ }
+ }
+
+ return target
+
+ }
+
+ isValidCloneTarget(widget) {
+
+ return !(widget.contains(this) || this.contains(widget))
+
+ }
+
+ createClone(init) {
+
+ if (this.cloneLock) return
+
+ this.cloneLock = true
+
+ var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')}
+
+ parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ this.updateContainer(!init)
+
+ this.cloneLock = false
+
+ }
+
+ unbindTarget() {
+
+ if (!this.cloneTarget) return
+
+ this.cloneTarget.off(undefined, undefined, this)
+
+ this.cloneTarget = null
+
+ }
+
+ bindTarget(target) {
+
+ if (!target) return
+
+ this.cloneTarget = target
+
+ // listen for cloneTarget's deletion
+ // if it is just edited, its recreation will be catched by the global 'widget-created' event handler
+ this.cloneTarget.on('widget-removed', (e)=>{
+ if (this.cloneTarget === e.widget) {
+ this.unbindTarget()
+ }
+ }, {context: this})
+
+ // listen for cloneTarget's content updates
+ this.cloneTarget.on('widget-created', (e)=>{
+
+ var {widget} = e,
+ parent = widget.parent
+
+ while (parent !== this.cloneTarget && parent !== widgetManager) {
+ // if updated widget is in a nested clone, ignore it:
+ // it will be handled by the nested clone that targets it
+ if (parent.getProp('type') === 'clone') return
+ parent = parent.parent
+ }
+
+ this.updateClone()
+
+ }, {context: this})
+
+ }
+
+ updateClone(options) {
+
+ if (this.cloneLock) return
+
+ this.cloneLock = true
+
+ var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')},
+ clone = this.children[0]
+
+ var delta = diff.diff(clone.props, data) || {},
+ [widget, patch] = diffToWidget(clone, delta),
+ changedProps = Object.keys(patch)
+
+ if (changedProps.length) {
+
+ diff.patch(widget.props, patch)
+
+
+ if (changedProps.some(x => !widget.isDynamicProp(x))) {
+
+ clone.reCreateWidget({reuseChildren: false})
+ this.updateContainer(false)
+
+ } else {
+
+ widget.updateProps(changedProps, this, options)
+ this.updateContainer(true)
+
+ }
+
+ }
+
+
+
+ this.cloneLock = false
+
+ }
+
+ updateContainer(checkResize) {
+
+
+ if (this.cloneTarget) {
+
+ var classes = [...this.cloneTarget.container.classList].filter(i=>excludedCloneClasses.indexOf(i) === -1)
+
+ if (!deepEqual(classes, this.cloneClass)) {
+ this.container.classList.remove(...this.cloneClass)
+ this.cloneClass = classes
+ this.container.classList.add(...this.cloneClass)
+ }
+
+ this.container.classList.remove('empty')
+
+ for (var w of this.getAllChildren()) {
+ w.container.classList.add('not-editable')
+ }
+
+ if (checkResize) resize.check(this.widget)
+
+ } else if (this.cloneClass.length) {
+
+ this.container.classList.remove(...this.cloneClass)
+ this.container.classList.add('empty')
+ this.cloneClass = []
+ this.widget.innerHTML = ''
+ widgetManager.removeWidgets(this.getAllChildren())
+
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'widgetId':
+ this.unbindTarget()
+ this.updateContainer(false)
+ this.bindTarget(this.getCloneTarget())
+ if (this.cloneTarget) this.createClone()
+ return
+ case 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ case 'colorBg':
+ case 'lineWidth':
+ case 'padding':
+ for (var w of this.children) {
+ if (w) w.onPropChanged(propName)
+ }
+ return
+
+ }
+
+ }
+
+ onRemove(){
+
+ this.unbindTarget()
+ super.onRemove()
+
+ }
+
+}
+
+Clone.dynamicProps = Clone.prototype.constructor.dynamicProps.concat(
+ 'widgetId'
+)
+
+module.exports = Clone
diff --git a/src/client/widgets/containers/keyboard.js b/src/client/widgets/containers/keyboard.js
new file mode 100644
index 00000000..27711a84
--- /dev/null
+++ b/src/client/widgets/containers/keyboard.js
@@ -0,0 +1,127 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ parser = require('../../parser')
+
+
+module.exports = class Keyboard extends Panel {
+
+ static description() {
+
+ return 'Piano keyboard.'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'keyboard',
+
+ keys: {type: 'number', value: 25, help: 'Defines the number keys'},
+ start: {type: 'number', value: 48, help: [
+ 'MIDI note number to start with (default is C4)',
+ 'Standard keyboards settings are: `[25, 48]`, `[49, 36]`, `[61, 36]`, `[88, 21]`'
+ ]},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ mode: {type: 'string', value: 'push', choices: ['push', 'toggle', 'tap'], help: [
+ 'Interraction mode:',
+ '- `push` (press & release)',
+ '- `toggle` (on/off switches)',
+ '- `tap` (no release)'
+ ]},
+
+ }, [], {
+
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--color-white:color;` (white keys color)',
+ '- `--color-black:color;` (black keys color)'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.childrenType = undefined
+ this.value = []
+
+ this.on('change',(e)=>{
+
+ if (e.widget === this) return
+
+ this.value[e.widget._index] = e.widget.getValue()
+ this.changed(e.options)
+
+ })
+
+ var start = parseInt(this.getProp('start')),
+ keys = parseInt(this.getProp('keys'))
+
+ var strData = JSON.stringify(options.props),
+ pattern = 'wbwbwwbwbwbw',
+ whiteKeys = 0, whiteKeys2 = 0, i
+
+ for (i = start; i < keys + start && i < 109; i++) {
+ if (pattern[i % 12] == 'w') whiteKeys++
+ }
+
+ this.container.style.setProperty('--nkeys', whiteKeys)
+
+ for (i = start; i < keys + start && i < 109; i++) {
+
+ var data = JSON.parse(strData)
+
+ data.top = data.left = data.height = data.width = 'auto'
+ data.type = 'button'
+ data.mode = this.getProp('mode')
+ data.id = this.getProp('id') + '/' + i
+ data.label = false
+ data.css = ''
+
+ data.target = '@{parent.target}'
+ data.decimals = '@{parent.decimals}'
+
+ data.address = '@{parent.address}'
+ data.preArgs = `JS{{
+ var a = @{parent.preArgs};
+ var b = typeof a === 'string' && a === '' ? [] : Array.isArray(a) ? a : [a];
+ return b.concat([${i}])
+ }}`
+
+ var key = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ key._index = i - start
+ key.container.classList.add('not-editable')
+ key.container.classList.add('key')
+
+ if (pattern[i % 12] == 'w') {
+ key.container.classList.add('white')
+ whiteKeys2++
+ } else {
+ key.container.classList.add('black')
+ key.container.style.setProperty('--rank', whiteKeys2)
+ }
+
+ this.value[i - start] = this.getProp('off')
+
+ }
+
+ }
+
+}
diff --git a/src/client/widgets/containers/matrix.js b/src/client/widgets/containers/matrix.js
new file mode 100644
index 00000000..9b66641d
--- /dev/null
+++ b/src/client/widgets/containers/matrix.js
@@ -0,0 +1,194 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ StaticProperties = require('../mixins/static_properties'),
+ parser = require('../../parser'),
+ {deepCopy} = require('../../utils')
+
+
+class Matrix extends StaticProperties(Panel, {scroll: false}) {
+
+ static description() {
+
+ return 'Generic matrix for creating rows/columns of widgets.'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'matrix',
+
+ widgetType: {type: 'string', value: 'button', help: 'Defines the type of the widgets in the matrix'},
+ quantity: {type: 'number', value: 4, help: 'Defines the number of widgets in the matrix'},
+ start: {type: 'integer', value: 0, help: 'First widget\'s index'},
+ props: {type: 'object', value: {}, help: [
+ 'Defines a set of property to override the widgets\' defaults.',
+ 'Formulas in this field are resolved with an extra variable representing each widget\'s index: `$`',
+ 'Note: by default, the widgets inherit from the matrix\' `id` and osc properties (`id` and `address` are appended with `/$`)'
+ ]},
+
+ _separator: 'layout',
+
+ layout: {type: 'string', value: 'horizontal', choices: ['horizontal', 'vertical', 'grid'], help: 'Defines how children are laid out.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+ innerPadding: {type : 'boolean', value: true, help: 'Set to `false` to make the `padding` property apply only between children and not at the container\'s inner boundaries.'},
+
+ }, [], {})
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.childrenType = undefined
+
+ this.value = []
+
+ this.on('change',(e)=>{
+
+ if (e.widget === this) return
+
+ if (this.getProp('widgetType') === 'clone') {
+
+ if (e.widget.parent.parent !== this) return
+
+ this.value[e.widget.parent._index] = e.widget.getValue()
+
+ } else {
+
+ if (e.widget.parent !== this) return
+
+ this.value[e.widget._index] = e.widget.getValue()
+
+
+ }
+
+ this.changed(e.options)
+
+ })
+
+
+
+ this.start = parseInt(this.getProp('start'))
+
+ if (parser.widgets[this.getProp('widgetType')]) {
+
+ for (let i = 0; i < this.getProp('quantity'); i++) {
+
+ var props = this.resolveProp('props', undefined, false, false, false, {'$':i + this.start})
+ var data = this.defaultProps(i + this.start)
+
+ if (typeof props === 'object' && props !== null) {
+ Object.assign(data, props)
+ }
+
+ var widget = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ widget._index = i
+ widget.container.classList.add('not-editable')
+
+ this.value[i] = widget.getValue()
+
+ }
+
+ } else {
+
+ this.errors.widgetType = this.getProp('widgetType') + ' is not a valid widget type'
+
+ }
+
+
+
+ }
+
+ defaultProps(i) {
+
+ return {
+ type: this.getProp('widgetType'),
+ id: '@{parent.id}/' + i,
+ address: '@{parent.address}/' + i,
+ preArgs: '@{parent.preArgs}',
+ target: '@{parent.target}',
+ decimals: '@{parent.decimals}',
+ bypass: '@{parent.bypass}',
+ label: i,
+ top: 'auto',
+ left: 'auto',
+ height: 'auto',
+ width: 'auto'
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'props':
+
+ for (let i = this.children.length - 1; i >= 0; i--) {
+
+ let data = this.resolveProp('props', undefined, false, false, false, {'$': i + this.start})
+
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
+ data = {}
+ }
+
+ if (typeof oldPropValue === 'object' && oldPropValue !== null) {
+ // if an overridden default props is removed, set it back to default
+ let overriddenDefaults,
+ widgetDefaults
+ for (var k in oldPropValue) {
+ if (data[k] === undefined) {
+ if (Matrix.overriddenDefaults.indexOf(k) !== -1) {
+ overriddenDefaults = overriddenDefaults || this.defaultProps(i + this.start)
+ data[k] = overriddenDefaults[k]
+ } else {
+ widgetDefaults = widgetDefaults || parser.defaults[data.type || this.getProp('widgetType')]
+ data[k] = deepCopy(widgetDefaults[k])
+ }
+ }
+ }
+ }
+
+ Object.assign(this.children[i].props, data)
+
+ this.children[i].updateProps(Object.keys(data), this, options)
+ // this.children[i] might have been recreated
+ this.children[i].container.classList.add('not-editable')
+
+ }
+
+ return
+
+ }
+
+ }
+
+}
+
+
+
+Matrix.overriddenDefaults = [
+ 'type', 'id', 'address', 'preArgs', 'target', 'decimals', 'bypass',
+ 'label', 'top', 'left', 'height', 'width'
+]
+
+Matrix.parsersContexts.props = {
+ $: 0
+}
+
+Matrix.dynamicProps = Matrix.prototype.constructor.dynamicProps.concat(
+ 'props'
+)
+
+module.exports = Matrix
diff --git a/src/client/widgets/containers/modal.js b/src/client/widgets/containers/modal.js
new file mode 100644
index 00000000..3e607638
--- /dev/null
+++ b/src/client/widgets/containers/modal.js
@@ -0,0 +1,285 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ {icon, iconify} = require('../../ui/utils'),
+ resize = require('../../events/resize'),
+ doubletab = require('../mixins/double_tap'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Modal extends Panel {
+
+ static description() {
+
+ return 'A toggle button that opens a popup panel. Cannot contain tabs directly.'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'modal',
+
+ label: {type: 'string|boolean', value: 'auto', help: [
+ 'Set to `false` to hide completely',
+ '- Insert icons using the prefix ^ followed by the icon\'s name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)',
+ '- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal`',
+ ]},
+ doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the modal require a double tap to open instead of a single tap'},
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ traversing: {type: 'boolean', value: false, help: 'Set to `true` to enable traversing gestures in this widget. Set to `smart` or `auto` to limit affected widgets by the type of the first touched widget'},
+
+ _separator: 'popup',
+
+ popupLabel: {type: 'string|boolean', value: 'auto', help: 'Alternative label for the modal popup'},
+ popupWidth: {type: 'number|percentage', value: '80%', help: 'Modal popup\'s size'},
+ popupHeight: {type: 'number|percentage', value: '80%', help: 'Modal popup\'s size'},
+ popupLeft: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
+ popupTop: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
+
+ _separator1: 'widget container',
+
+ layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal', 'grid'], help: 'Defines how children are laid out.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ contain: {type: 'boolean', value: true, help:'If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel.'},
+ scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
+ innerPadding: {type : 'boolean', value: true, help: 'Set to `false` to make the `padding` property apply only between children and not at the container\'s inner boundaries.'},
+
+ }, [], {
+
+ _children: 'children',
+
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object'},
+ value: {type: 'integer', value: '', help: [
+ 'Defines the modal\'s state:`0` for closed, `1` for opened'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.popup = html`
+
+ `
+
+ this.container.appendChild(this.popup)
+ this.popupContent = DOM.get(this.popup, '.popup-content')[0]
+
+ // convert dimensions / coordinates to rem
+ var geometry = {}
+ for (var g of ['Width', 'Height', 'Left', 'Top']) {
+ geometry[g] = parseFloat(this.getProp('popup' + g)) == this.getProp('popup' + g) ? parseFloat(this.getProp('popup' + g)) + 'rem' : this.getProp('popup' + g)
+ }
+
+ this.popup.style.setProperty('--width', geometry.Width)
+ this.popup.style.setProperty('--height', geometry.Height)
+
+ if (geometry.Left !== 'auto') {
+ this.popup.style.setProperty('--left', geometry.Left)
+ this.popup.classList.add('x-positionned')
+ }
+
+ if (geometry.Top !== 'auto') {
+ this.popup.style.setProperty('--top', geometry.Top)
+ this.popup.classList.add('y-positionned')
+ }
+
+ this.toggle = this.container.appendChild(html`
`)
+
+ if (this.getProp('doubleTap')) {
+ doubletab(this.toggle, ()=>{
+ this.setValue(1, {sync:true, send:true})
+ })
+ } else {
+ this.toggle.addEventListener('fast-click',(e)=>{
+ if (e.capturedByEditor === true) return
+ e.detail.preventOriginalEvent = true
+ this.setValue(1, {sync:true, send:true})
+ })
+ }
+
+ var closer = DOM.get(this.popup, '.closer')[0]
+ this.popup.addEventListener('fast-click',(e)=>{
+ if ((e.target === this.popup || e.target === closer) && this.value == 1) {
+ e.detail.preventOriginalEvent = true
+ this.setValue(0, {sync:true, send:true})
+ }
+ })
+
+ this.escapeKeyHandler = ((e)=>{
+ if (e.keyCode==27) this.setValue(0, {sync:true, send:true})
+ }).bind(this)
+
+ this.value = 0
+ this.init = false
+ this.labelChange = true
+
+
+ this.popupContent.classList.add('layout-' + this.getProp('layout'))
+ this.popupContent.style.setProperty('--widget-padding', this.getProp('padding') != 'auto' ? parseFloat(this.getProp('padding')) + 'rem' : '')
+
+ this.label = html` `
+ this.updateLabel()
+
+ this.childrenType = 'widget'
+
+ }
+
+
+ isVisible() {
+
+ return this.init && this.value && super.isVisible()
+
+ }
+
+ setValue(v, options={}) {
+
+ if (this.init === undefined) return
+
+ this.value = v ? 1 : 0
+
+ if (!this.init && this.value) {
+ this.popupContent.appendChild(this.widget)
+ this.init = true
+ }
+
+ if (this.value && this.labelChange) {
+ this.updatePopupLabel()
+ }
+
+ this.popup.classList.toggle('show', this.value)
+ this.container.classList.toggle('on', this.value)
+
+ this.bindEscKey(this.value)
+
+ if (this.init) this.fixParents()
+
+ this.setVisibility()
+ if (this.value) {
+ resize.check(this.widget, true)
+ }
+
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+
+ }
+
+ fixParents() {
+
+ var parent = this.parent
+
+ while (parent && parent.props && !parent.getProp('type').match(/tab|root/)) {
+
+ parent.modalBreakout += (this.value ? 1 : -1)
+ if (parent.modalBreakout > 0) parent.container.classList.add('modal-breakout')
+ else if (parent.modalBreakout === 0) parent.container.classList.remove('modal-breakout')
+ else parent.modalBreakout = 0
+
+ parent = parent.parent
+ }
+
+
+ this.modalBreakout += (this.value ? 1 : -1)
+ if (this.modalBreakout > 0) this.container.classList.add('modal-breakout')
+ else if (this.modalBreakout === 0) this.container.classList.remove('modal-breakout')
+ else this.modalBreakout = 0
+
+
+ }
+
+ bindEscKey(set) {
+
+ if (set) {
+ document.addEventListener('keydown', this.escapeKeyHandler)
+ } else {
+ document.removeEventListener('keydown', this.escapeKeyHandler)
+ }
+
+ }
+
+ onRemove() {
+ this.bindEscKey(false)
+ this.setValue(0)
+ super.onRemove()
+ }
+
+ updateLabel() {
+
+ if (this.getProp('label') === false) {
+
+ if (this.container.contains(this.label)) this.container.removeChild(this.label)
+
+ } else {
+ this.label.innerHTML = this.getProp('label') == 'auto'?
+ this.getProp('id'):
+ iconify(String(this.getProp('label')).replace(/`})
+
+ this.childrenType = ''
+
+ this.container.classList.toggle('no-inner-padding', !this.getProp('innerPadding'))
+ this.container.classList.toggle('no-scroll', !this.getProp('scroll'))
+ this.container.classList.add('layout-' + this.getProp('layout'))
+ this.container.classList.toggle('layout-contain', this.getProp('contain'))
+
+ this.modalBreakout = 0
+
+ var layout = this.getProp('layout')
+ if (layout === 'grid') {
+
+ var template = this.getProp('gridTemplate') || 2
+ this.widget.style.gridTemplate = template === parseInt(template) ? `none / repeat(${template}, 1fr)` : template
+
+ } else if (layout === 'vertical' || layout === 'horizontal'){
+
+ var justify = this.getProp('justify')
+ if (justify === 'start' || justify === 'end') justify = 'flex-' + justify
+ this.widget.style.justifyContent = justify
+
+ }
+
+ if (this.getProp('tabs') && this.getProp('tabs').length) {
+
+ this.container.classList.add('contains-tabs')
+ this.container.classList.toggle('vertical-tabs', this.getProp('verticalTabs'))
+
+ } else {
+
+ this.container.classList.add('contains-widgets')
+
+ }
+
+
+
+
+ this.tabs = []
+
+ if (this.getProp('tabs') && this.getProp('tabs').length) {
+
+ this.childrenType = 'tab'
+
+ this.value = -1
+
+ this.navigation = this.widget.appendChild(html`
`)
+
+ this.children = options.children || new Array(this.getProp('tabs').length)
+ for (let i = 0; i < this.children.length; i++) {
+ if (this.children[i]) {
+ this.widget.appendChild(this.children[i].container)
+ this.children[i].mounted = true
+ this.children[i].parent = this
+ this.children[i].parentNode = this.widget
+ } else {
+ parser.parse({
+ data: this.getProp('tabs')[i],
+ parentNode: this.widget,
+ parent: this,
+ tab: true,
+ index: i
+ })
+ }
+ }
+
+ if (options.children) this.alignChildrenProps()
+
+ this.createNavigation()
+
+ this.navigation.addEventListener('fast-click', (e)=>{
+ if (!e.target.hasAttribute('data-widget')) return
+ var index = DOM.index(e.target)
+ this.setValue(index, {sync: true, send:this.value != index})
+ })
+
+ this.on('tab-created', (e)=>{
+ this.createNavigation()
+ e.stopPropagation = true
+ })
+
+ this.setValue(this.getProp('value') || 0)
+
+ } else if (this.getProp('widgets') && this.getProp('widgets').length) {
+
+ this.value = -1
+
+ this.childrenType = 'widget'
+
+ this.children = options.children || new Array(this.getProp('widgets').length)
+ for (let i = 0; i < this.children.length; i++) {
+ if (this.children[i]) {
+ this.widget.appendChild(this.children[i].container)
+ this.children[i].mounted = true
+ this.children[i].parent = this
+ this.children[i].parentNode = this.widget
+ } else {
+ parser.parse({
+ data: this.getProp('widgets')[i],
+ parentNode: this.widget,
+ parent: this,
+ index: i
+ })
+ }
+ }
+
+ if (options.children) this.alignChildrenProps()
+
+
+ }
+
+ if (this.getProp('traversing')) this.setTraversing()
+
+ }
+
+ createNavigation() {
+
+ this.navigation.innerHTML = ''
+ this.tabs = []
+
+ DOM.each(this.widget, '> .widget', (tab)=>{
+
+ let widget = widgetManager.getWidgetByElement(tab),
+ style = ''
+
+ style += widget.getProp('colorWidget') === 'auto' ? '' : `--color-widget:${widget.getProp('colorWidget')};`
+ style += widget.getProp('colorFill') === 'auto' ? '' : `--color-fill:${widget.getProp('colorFill')};`
+ style += widget.getProp('colorText') === 'auto' ? '' : `--color-text:${widget.getProp('colorText')};`
+
+ if (!widget.getProp('visible')) style += 'display:none;'
+
+ this.tabs.push(widget)
+ var label = html`
+
+
+ `
+ label.innerHTML = widget.label
+ this.navigation.appendChild(label)
+
+ })
+
+
+ this.setValue(this.value)
+
+ }
+
+ setValue(v, options={}) {
+ if (this.tabs.length && typeof v == 'number' && v >= 0 && v < this.tabs.length) {
+
+ for (let i in this.tabs) {
+ if (i != v) this.tabs[i].hide()
+ }
+
+ this.value = v
+
+ this.tabs[v].show()
+ DOM.each(this.navigation, 'div', (el)=>{el.classList.remove('on')})[v].classList.add('on')
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+ }
+
+ scroll(s) {
+
+ if (!s) {
+ return [this.widget.scrollLeft, this.widget.scrollTop]
+ } else {
+ if (s[0] !== undefined) this.widget.scrollLeft = s[0]
+ if (s[1] !== undefined) this.widget.scrollTop = s[1]
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'traversing':
+ this.setTraversing()
+ return
+
+ case 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ case 'colorBg':
+ case 'padding':
+ for (var w of this.children) {
+ if (w) w.onPropChanged(propName)
+ }
+ return
+
+ }
+
+ }
+
+ setCssVariables() {
+
+ super.setCssVariables()
+ setScrollbarColor(this.container)
+
+ }
+
+ setTraversing(update) {
+
+ var traversing = this.getProp('traversing')
+
+ disableTraversingGestures(this.widget)
+
+ if (traversing) {
+ enableTraversingGestures(this.widget, {type: typeof traversing === 'string' ? traversing : undefined})
+ }
+
+ }
+
+
+ onRemove() {
+ this.off('resize')
+ super.onRemove()
+ }
+
+}
+
+Panel.dynamicProps = Panel.prototype.constructor.dynamicProps.concat(
+ 'variables',
+ 'traversing'
+)
+
+module.exports = Panel
diff --git a/src/client/widgets/containers/patchbay.js b/src/client/widgets/containers/patchbay.js
new file mode 100644
index 00000000..12703ef6
--- /dev/null
+++ b/src/client/widgets/containers/patchbay.js
@@ -0,0 +1,334 @@
+var Widget = require('../common/widget'),
+ Canvas = require('../common/canvas'),
+ Container = require('../common/container'),
+ {iconify} = require('../../ui/utils'),
+ parser = require('../../parser'),
+ html = require('nanohtml')
+
+class PatchBayNode extends Widget {
+
+
+ static defaults() {
+
+ return super.defaults({
+ label: {type: 'string', value: ''}
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.widget.innerHTML = iconify(this.getProp('label').replace(//g, '>').replace(/\n/g,' '))
+
+ this.value = []
+
+ }
+
+ setValue(v, options={} ) {
+
+ this.value = Array.isArray(v) ? v : v ? [v] : []
+
+ var allowed = this.parent.getProp('outputs')
+ for (var i = this.value.length -1; i > -1; i--) {
+ if (allowed.indexOf(this.value[i]) === -1) {
+ this.value.splice(i, 1)
+ }
+ }
+
+ this.parent.batchDraw()
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ toggleValue(v) {
+
+ var index = this.value.indexOf(v)
+
+ if (index > -1) {
+ this.value.splice(index, 1)
+ } else {
+ this.value.push(v)
+ }
+
+ this.setValue(this.value, {sync: true, send: true})
+
+ }
+
+
+}
+
+class PatchBay extends Container(Canvas) {
+
+ static description() {
+
+ return 'Connect inputs to outputs.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'patchbay',
+
+ inputs: {type: 'array|object', value: ['input_1', 'input_2'], help: [
+ '- `Array` of input names : `[\'input_1\', \'input_2\']`',
+ '- `Object` of `"label_1": "input_1"` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ '',
+ 'Patchbay inputs can be connected to one or more outputs and will send messages of the following form when they are connected/disconnected: ',
+ '`/patchbay_address input_x output_x output_y etc`',
+ 'If no output is connected to the input, the message will be `/patchbay_address input_x`',
+ 'The inputs values can be consumed with the property inheritance syntax: `@{patchbay_id/input_1}` returns an array of output names connected to `input_1`'
+ ]},
+ outputs: {type: 'array|object', value: ['output_1', 'output_2'], help: 'List of output values the inputs can connect to (see `inputs`).'},
+
+ }, [], {
+
+ css: {type: 'string', value: '', help: [
+ 'The inputs/ouputs width can be adjusted by using the `.nodes` selector:',
+ '`.nodes { width: 25% }`',
+ ]}
+ })
+
+ }
+
+ static normalizeArrayObject(obj) {
+
+ if (typeof obj !== 'object' || obj === null) {
+ return PatchBay.normalizeArrayObject([obj])
+ } else if (Array.isArray(obj)) {
+ var ret = {},
+ k, i
+ for (i = 0; i < obj.length; i++) {
+ k = typeof obj[i] === 'string' ? obj[i] : JSON.stringify(obj[i])
+ ret[k] = obj[i]
+ }
+ return ret
+ } else {
+ return obj
+ }
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+
+
+ `})
+
+ this.inputs = PatchBay.normalizeArrayObject(this.getProp('inputs'))
+ this.outputs = PatchBay.normalizeArrayObject(this.getProp('outputs'))
+ this.inputsValues = Object.values(this.inputs)
+ this.outputsValues = Object.values(this.outputs)
+
+ this.inputsWidgets = []
+ this.inputNodes = []
+ this.outputNodes = []
+
+
+ for (let k in this.inputs) {
+ let w = parser.parse({
+ data: {
+ type: 'patchbaynode',
+ id: this.getProp('id') + '/' + this.inputs[k],
+ address: '@{parent.address}',
+ target: '@{parent.target}',
+ preArgs: this.inputs[k],
+ bypass: '@{parent.bypass}',
+ label: k
+
+ },
+ parentNode: DOM.get(this.widget, '.inputs')[0],
+ parent: this
+ })
+ w.container.classList.add('not-editable')
+ this.inputsWidgets.push(w)
+ this.inputNodes.push(w.container)
+ }
+
+ var outputs = DOM.get(this.widget, '.outputs')[0]
+ for (let k in this.outputs) {
+ var node = html`
+
+ ${k}
+
+ `
+ outputs.appendChild(node)
+ this.outputNodes.push(node)
+ }
+
+
+ this.connecting = []
+
+ this.widget.addEventListener('fast-click', (e)=>{
+ this.toggleConnection(e.target)
+ e.stopPropagation()
+ })
+
+
+ this.mousePosition = []
+ this.on('drag', (e)=>{
+ if (!this.connecting.length) {
+ this.toggleConnection(e.target)
+ }
+ if (e.target === this.canvas) {
+ this.mousePosition = [e.offsetX, e.offsetY]
+ } else if (this.mousePosition.length) {
+ this.mousePosition[0] += e.movementX
+ this.mousePosition[1] += e.movementY
+ }
+ this.batchDraw()
+ }, {element: this.widget})
+ this.on('dragend', (e)=>{
+ if (this.mousePosition.length) {
+ this.mousePosition = []
+ this.toggleConnection(e.target)
+ }
+ }, {element: this.widget})
+
+
+ }
+
+ toggleConnection(node) {
+
+ var input = this.inputNodes.indexOf(node),
+ output = this.outputNodes.indexOf(node)
+
+ if (input > -1 && input !== this.connecting[0]) {
+ this.connecting[0] = input
+ } else if (output > -1 && output !== this.connecting[1]) {
+ this.connecting[1] = output
+ } else {
+ this.connecting = []
+ }
+
+ if (this.connecting[0] !== undefined && this.connecting[1] !== undefined) {
+ this.inputsWidgets[this.connecting[0]].toggleValue(this.outputsValues[this.connecting[1]])
+ this.connecting = []
+ } else {
+ this.batchDraw()
+ }
+
+ if (this.connecting.length) {
+ var cb = (e)=>{
+ this.toggleConnection()
+ document.removeEventListener('fast-click', cb)
+ }
+ document.addEventListener('fast-click', cb)
+ }
+
+ }
+
+ draw() {
+
+ this.clear()
+
+ var x1 = 0,
+ x2 = this.width,
+ y1, y2,
+ connections,
+ i, j
+
+ var lines = [],
+ strongLines = []
+
+ for (i = 0; i < this.inputsWidgets.length; i++) {
+
+ connections = this.inputsWidgets[i].getValue()
+
+ if (connections.length) {
+
+ y1 = this.height / this.inputsValues.length * (i + 0.5)
+
+ for (j = 0; j < connections.length; j++) {
+
+ if (this.outputsValues.indexOf(connections[j]) > -1) {
+
+ y2 = this.height / this.outputsValues.length * (this.outputsValues.indexOf(connections[j]) + 0.5)
+
+ var line = [[x1, y1], [this.width / 2, y1, this.width / 2, y2 ,x2, y2]]
+
+ if (this.connecting[0] === i || this.connecting[1] === this.outputsValues.indexOf(connections[j])) {
+ strongLines.push(line)
+ } else {
+ lines.push(line)
+ }
+
+ }
+
+ }
+
+
+ }
+
+ }
+
+ if (this.connecting.length) {
+
+ this.ctx.beginPath()
+ this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+
+ var side = this.connecting[0] !== undefined ? 0 : 1,
+ cx = side === 0 ? 0 : this.width,
+ cy = this.height / (side === 0 ? this.inputsValues : this.outputsValues).length * (this.connecting[side] + 0.5)
+
+ this.ctx.arc(cx, cy, 8 * PXSCALE, Math.PI * 2, false)
+ this.ctx.fill()
+ strongLines.push(null)
+
+
+ if (this.mousePosition.length) {
+ var [x3, y3] = this.mousePosition,
+ centerx = Math.abs(cx - x3) / 2,
+ bz1 = side ? cx - centerx : cx + centerx,
+ bz2 = side ? x3 + centerx : x3 - centerx
+
+ strongLines.push([[cx, cy], [bz1, cy, bz2, y3 ,x3, y3]])
+
+ }
+
+ }
+
+
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = 2 * PXSCALE
+ this.ctx.globalAlpha = strongLines.length ? this.cssVars.alphaFillOff : this.cssVars.alphaFillOn
+
+ this.ctx.beginPath()
+ for (i in lines) {
+ this.ctx.moveTo(...lines[i][0])
+ this.ctx.bezierCurveTo(...lines[i][1])
+ }
+ this.ctx.stroke()
+
+ if (strongLines.length) {
+
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ for (i in strongLines) {
+ if (strongLines[i] === null) continue
+ this.ctx.moveTo(...strongLines[i][0])
+ this.ctx.bezierCurveTo(...strongLines[i][1])
+ }
+ this.ctx.stroke()
+
+ }
+
+
+ }
+
+}
+
+module.exports = {
+ PatchBay,
+ PatchBayNode
+}
diff --git a/src/client/widgets/containers/root.js b/src/client/widgets/containers/root.js
new file mode 100644
index 00000000..f9d59fc6
--- /dev/null
+++ b/src/client/widgets/containers/root.js
@@ -0,0 +1,81 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ StaticProperties = require('../mixins/static_properties')
+
+class Root extends StaticProperties(Panel, {visible: true, label: false, id: 'root'}) {
+
+ static description() {
+
+ return 'Main (unique) container'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'panel',
+
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ traversing: {type: 'boolean', value: false, help: 'Set to `true` to enable traversing gestures in this widget. Set to `smart` or `auto` to limit affected widgets by the type of the first touched widget'},
+
+ _separator1: 'widget container',
+
+ layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal', 'grid'], help:'Defines how children are laid out.'},
+ justify: {type: 'string', value: 'start', choices: ['start', 'end', 'center', 'space-around', 'space-between'], help:'If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ contain: {type: 'boolean', value: true, help:'If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel.'},
+ scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
+ innerPadding: {type : 'boolean', value: true, help: 'Set to `false` to make the `padding` property apply only between children and not at the container\'s inner boundaries.'},
+
+ _separator2: 'tab container',
+
+ verticalTabs: {type: 'boolean', value: false, help: 'Set to `true` to display for vertical tab layout'},
+
+ }, [
+ 'visible', 'label',
+ 'left', 'top', 'expand',
+ 'colorFill', 'colorStroke', 'alphaStroke', 'alphaFillOff',
+ ], {
+
+ _children:'children',
+
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously.'},
+ tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously'},
+
+ value: {type: 'integer', value: '', help: [
+ 'Defines currently widgeted tab in the widget',
+ 'A tab can be opened only by setting its parent\'s value'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ options.root = true
+ options.props.id = 'root'
+
+ super(options)
+
+ this.widget.classList.add('root')
+
+
+ DOM.each(this.widget, '> .navigation', (el)=>{
+ el.classList.add('main')
+ })
+
+ }
+
+ isVisible() {
+
+ return true
+
+ }
+
+
+}
+
+
+module.exports = Root
diff --git a/src/client/widgets/containers/tab.js b/src/client/widgets/containers/tab.js
new file mode 100644
index 00000000..75413a37
--- /dev/null
+++ b/src/client/widgets/containers/tab.js
@@ -0,0 +1,139 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ resize = require('../../events/resize'),
+ {iconify} = require('../../ui/utils')
+
+class Tab extends Panel {
+
+ static description() {
+
+ return 'Tabbed panel widget'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+
+ _class_specific: 'panel',
+
+ label: {type: 'string|boolean', value: 'auto', help: [
+ 'Set to `false` to hide completely',
+ '- Insert icons using the prefix ^ followed by the icon\'s name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)',
+ '- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal`',
+ ]},
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ traversing: {type: 'boolean', value: false, help: 'Set to `true` to enable traversing gestures in this widget. Set to `smart` or `auto` to limit affected widgets by the type of the first touched widget'},
+ // detached: {type: 'boolean', value: true, help: 'Set to `false` if the tab contains `frame` widgets that should not be reloaded when the tab opens'},
+
+ _separator1: 'widget container',
+
+ layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal', 'grid'], help:'Defines how children are laid out.'},
+ justify: {type: 'string', value: 'start', choices: ['start', 'end', 'center', 'space-around', 'space-between'], help:'If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ contain: {type: 'boolean', value: true, help:'If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel.'},
+ scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
+ innerPadding: {type : 'boolean', value: true, help: 'Set to `false` to make the `padding` property apply only between children and not at the container\'s inner boundaries.'},
+
+ _separator2: 'tab container',
+
+ verticalTabs: {type: 'boolean', value: false, help: 'Set to `true` to display for vertical tab layout'},
+
+ }, [
+ '_geometry', 'left', 'top', 'width', 'height', 'expand',
+ 'colorStroke', 'alphaStroke', 'alphaFillOff', 'alphaFillOn'
+ ], {
+
+ _children:'children',
+
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously.'},
+ tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously'},
+
+ value: {type: 'integer', value: '', help: [
+ 'Defines currently widgeted tab in the widget',
+ 'A tab can be opened only by setting its parent\'s value'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.container.classList.add('show')
+
+ this.detached = false
+
+ this.label = ''
+ this.updateLabel()
+
+ }
+
+ updateLabel() {
+
+ if (this.getProp('label') === false) {
+ this.label = ''
+ } else {
+ this.label = this.getProp('label') == 'auto'?
+ this.getProp('id'):
+ iconify(String(this.getProp('label')).replace(/
+
+ `
+ })
+
+ if (!this.getProp('border')) this.container.classList.add('noborder')
+
+ this.frame = DOM.get(this.widget, '.frame')[0]
+ this.errorText = html`${locales('iframe_unauthorized')}`
+ this.errorTextMounted = false
+
+
+ }
+
+ setValue(v, options={}) {
+
+ this.value = v
+
+ if (this.value) {
+ this.frame.setAttribute('src', this.value)
+ this.widget.classList.remove('error')
+ if (this.errorTextMounted) {
+ this.widget.removeChild(this.errorText)
+ this.errorTextMounted = false
+ }
+ } else {
+ this.frame.setAttribute('src', '')
+ this.widget.classList.add('error')
+ this.widget.appendChild(this.errorText)
+ this.errorTextMounted = true
+ }
+
+ if (options.sync) this.changed(options)
+
+ }
+
+
+}
+
+module.exports = Frame
diff --git a/src/client/widgets/frames/html.js b/src/client/widgets/frames/html.js
new file mode 100644
index 00000000..fc36d477
--- /dev/null
+++ b/src/client/widgets/frames/html.js
@@ -0,0 +1,90 @@
+var Widget = require('../common/widget'),
+ morph = require('nanomorph'),
+ html = require('nanohtml'),
+ sanitizeHtml = require('sanitize-html'),
+ StaticProperties = require('../mixins/static_properties')
+
+var sanitizeOptions = {
+ allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2']).filter(x=>x!=='iframe'),
+ allowedAttributes: {
+ '*': [ 'title', 'class', 'style'],
+ 'img': [ 'src' , 'title', 'class', 'style', 'width', 'height']
+ }
+}
+
+class Html extends StaticProperties(Widget, {bypass: true}) {
+
+ static description() {
+
+ return 'Simple HTML parser.'
+
+ }
+
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'html',
+
+ html: {type: 'string', value: '', help: [
+ 'Allowed HTML tags:',
+ ' h1-6, blockquote, p, a, ul, ol, nl, li,',
+ ' b, i, strong, em, strike, code, hr, br, div,',
+ ' table, thead, img, caption, tbody, tr, th, td, pre',
+ 'Allowed attributes:',
+ ' <*>: class, style, title',
+ ' : src, width, height',
+ ]},
+
+ }, ['decimals', 'typeTags', 'bypass', 'ignoreDefaults'], {})
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ if (!this.getProp('border')) this.container.classList.add('noborder')
+ this.frame = DOM.get(this.widget, '.frame')[0]
+
+ if (this.getProp('html') !== '') this.updateHtml()
+
+ }
+
+ updateHtml(){
+
+ var newHtml = this.frame.cloneNode(false)
+
+ newHtml.innerHTML = sanitizeHtml(this.getProp('html'), sanitizeOptions)
+
+ morph(this.frame, newHtml)
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'html':
+ this.updateHtml()
+ return
+
+ }
+
+ }
+
+
+}
+
+Html.dynamicProps = Html.prototype.constructor.dynamicProps.concat(
+ 'html'
+)
+
+module.exports = Html
diff --git a/src/client/widgets/frames/image.js b/src/client/widgets/frames/image.js
new file mode 100644
index 00000000..da396f08
--- /dev/null
+++ b/src/client/widgets/frames/image.js
@@ -0,0 +1,105 @@
+var Widget = require('../common/widget'),
+ html = require('nanohtml'),
+ {urlParser} = require('../utils'),
+ StaticProperties = require('../mixins/static_properties')
+
+module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
+
+ static description() {
+
+ return 'Load a image (url or base64-encoded).'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'image',
+
+ size: {type: 'string', value: 'cover', help: 'CSS background-size'},
+ position: {type: 'string', value: 'center', help: 'CSS background-position'},
+ repeat: {type: 'string', value: 'no-repeat', help: 'CSS background-repeat'},
+ cache: {type: 'boolean', value: true, help: [
+ 'Set to false to disable image caching (forces file reload when updating or editing the widget).',
+ 'When true, sending `reload` to the widget reloads its image without changing its value'
+ ]}
+
+ }, ['decimals', 'typeTags', 'bypass', 'ignoreDefaults'], {
+
+ value: {type: 'string', value: '', help: [
+ '- File `url` or `path` (relative to the session file location by default, falling back to absolute path)',
+ '- Base64 encoded image : `data:image/...`'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ if (!this.getProp('border')) this.container.classList.add('noborder')
+ this.frame = DOM.get(this.widget, '.frame')[0]
+
+ this.frame.style.setProperty('background-size', this.getProp('size'))
+ this.frame.style.setProperty('background-position', this.getProp('position'))
+ this.frame.style.setProperty('background-repeat', this.getProp('repeat'))
+
+ }
+
+ setValue(v, options={}) {
+
+ if (typeof this.value !== 'string') return
+
+ var s = v==null ? '' : '' + v,
+ cache_query = ''
+
+ if (!s.length) {
+
+ this.value = this.getProp('default')
+
+ } else if (s != 'reload') {
+
+ if (s.length > 1) this.value = s
+
+ }
+
+ if (typeof this.value === 'string' && this.value.length) {
+
+ if ((s === 'reload' || !this.getProp('cache')) && this.value.indexOf('base64') === -1) {
+ cache_query = (this.value.indexOf('?') != -1 ? '&' : '?') + Date.now()
+ }
+
+ }
+
+ var url = this.value,
+ parser = urlParser(url)
+
+ // escpape windows absolute file paths
+ if (!parser.protocol.match(/http|data/)) url = url.replace(':', '_:_')
+ url = url.replace(/\\/g, '\\\\')
+
+
+ if (url) {
+ this.frame.style.setProperty('background-image', `url("${url}${cache_query}")`)
+ } else {
+ this.frame.style.setProperty('background-image', '')
+ }
+
+ if (options.sync) this.changed(options)
+
+ }
+
+ onRemove() {
+
+ super.onRemove()
+
+ }
+
+}
diff --git a/src/client/widgets/frames/svg.js b/src/client/widgets/frames/svg.js
new file mode 100644
index 00000000..83b3f5db
--- /dev/null
+++ b/src/client/widgets/frames/svg.js
@@ -0,0 +1,108 @@
+var Widget = require('../common/widget'),
+ morph = require('nanomorph'),
+ html = require('nanohtml'),
+ StaticProperties = require('../mixins/static_properties')
+
+
+class Svg extends StaticProperties(Widget, {bypass: true}) {
+
+ static description() {
+
+ return 'Svg parser.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'svg',
+
+ svg: {type: 'string', value: '', help: [
+ 'Svg xml definition (will be wrapped in a `< svg />` element)',
+ ]},
+
+ }, ['decimals', 'typeTags', 'bypass', 'ignoreDefaults'], {})
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.frame = DOM.get(this.widget, '.frame')[0]
+
+ this.height = undefined
+ this.width = undefined
+
+ this.on('resize', this.resizeHandleProxy.bind(this), {element: this.widget})
+
+ if (!this.getProp('border')) this.container.classList.add('noborder')
+
+ }
+
+ updateSvg(force){
+
+ if (!this.width || !this.height) return
+
+ var svg = this.getProp('svg')
+
+ this.frame.setAttribute('width', this.width)
+ this.frame .setAttribute('height', this.height)
+
+ var node = this.frame.cloneNode(false)
+
+ node.innerHTML = svg
+
+ if (force) {
+ this.frame.innerHTML = node.innerHTML
+ } else {
+ morph(this.frame, node)
+ }
+
+ }
+
+ resizeHandleProxy() {
+
+ this.resizeHandle(...arguments)
+
+ }
+
+ resizeHandle(event){
+
+ var {width, height} = event
+
+ this.height = height
+ this.width = width
+
+ this.updateSvg(true)
+
+ }
+
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'svg':
+ this.updateSvg()
+ return
+
+ }
+
+ }
+
+
+}
+
+Svg.dynamicProps = Svg.prototype.constructor.dynamicProps.concat(
+ 'svg'
+)
+
+module.exports = Svg
diff --git a/src/client/widgets/graphs/eq.js b/src/client/widgets/graphs/eq.js
new file mode 100644
index 00000000..fd381f6d
--- /dev/null
+++ b/src/client/widgets/graphs/eq.js
@@ -0,0 +1,237 @@
+var {mapToScale} = require('../utils'),
+ Plot = require('./plot'),
+ Widget = require('../common/widget'),
+ StaticProperties = require('../mixins/static_properties')
+
+class Eq extends StaticProperties(Plot, {logScaleX: false, logScaleY:false, smooth:true}) {
+
+ static description() {
+
+ return 'Draws logarithmic frequency response from an array of filter objects.'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'eq',
+
+ filters: {type: 'array', value: '', help: [
+ 'Each item must be an object with the following properties',
+ '- `type`: string ("highpass", "highshelf", "lowpass", "lowshelf", "peak", "bandpass" or "notch", default: "peak")',
+ '- `freq`: number (filter\'s resonant frequency, default: 1000)',
+ '- `q`: number (Q factor, default: 1)',
+ '- `gain`: number (default: 0)',
+ '- `on`: boolean (default: true)',
+ 'See https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode'
+
+ ]},
+ pips: {type: 'boolean', value: true, help: 'Set to false to hide the scale'},
+ rangeX: {type: 'object', value: {min: 20, max: 22000}, help: 'Defines the min and max values for the x axis (in Hz, logarithmic scale)'},
+ rangeY: {type: 'object', value: {min:-6, max:6}, help: 'Defines the min and max values for the y axis (in dB)'},
+ origin: {type: 'number|boolean', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
+
+ }, ['interaction', 'decimals', 'typeTags', 'bypass', 'ignoreDefaults'])
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.calcResponse()
+
+ }
+
+ calcResponse() {
+
+ var resolution = this.width,
+ frequencyHz = new Float32Array(resolution),
+ filterResponse = new Float32Array(resolution).fill(0)
+
+ for (let i = 0; i < resolution; ++i) {
+ frequencyHz[i] = mapToScale(i, [0, this.width], [this.getProp('rangeX').min, this.getProp('rangeX').max], -1, true)
+ }
+
+ for (let filter of this.getProp('filters')) {
+
+ if (filter.on !== undefined && !filter.on) continue
+
+ biquadResponse({
+ type: filter.type || 'peak',
+ gain: filter.gain || 0,
+ frequency: filter.freq || 1000,
+ q: filter.q || 1
+ }, frequencyHz, filterResponse)
+
+ }
+
+ this.setValue(filterResponse, {sync: true})
+
+
+
+ }
+
+ setValue(v, options={}) {
+
+ if (!(v instanceof Float32Array) && !(Array.isArray(v)) || v.length !== this.width) return
+
+ this.value = v
+ this.batchDraw()
+
+ if (options.sync) this.changed(options)
+
+ }
+
+ resizeHandle(event){
+
+ super.resizeHandle(event)
+ if (this.width !== this.value.length) this.calcResponse()
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ super.onPropChanged(...arguments)
+
+ switch (propName) {
+ case 'filters':
+ this.calcResponse()
+ return
+
+ }
+
+ }
+
+}
+
+Eq.dynamicProps = Eq.prototype.constructor.dynamicProps.concat(
+ 'filters'
+)
+
+module.exports = Eq
+
+
+// biquadResponse
+// Based on code by Nigel Redmon Dec 14, 2010 njr
+function biquadResponse(options, frequencyHz, filterResponse) {
+
+ var {type, frequency, q, gain} = options,
+ Fs = 44100,
+ len = frequencyHz.length,
+ a0, a1, a2, b1, b2,norm
+
+ var V = Math.pow(10, Math.abs(gain) / 20)
+ var K = Math.tan(Math.PI * frequency / Fs)
+
+ switch (type) {
+ case 'lowpass':
+ norm = 1 / (1 + K / q + K * K)
+ a0 = K * K * norm
+ a1 = 2 * a0
+ a2 = a0
+ b1 = 2 * (K * K - 1) * norm
+ b2 = (1 - K / q + K * K) * norm
+ break
+
+ case 'highpass':
+ norm = 1 / (1 + K / q + K * K)
+ a0 = 1 * norm
+ a1 = -2 * a0
+ a2 = a0
+ b1 = 2 * (K * K - 1) * norm
+ b2 = (1 - K / q + K * K) * norm
+ break
+
+ case 'bandpass':
+ norm = 1 / (1 + K / q + K * K)
+ a0 = K / q * norm
+ a1 = 0
+ a2 = -a0
+ b1 = 2 * (K * K - 1) * norm
+ b2 = (1 - K / q + K * K) * norm
+ break
+
+ case 'notch':
+ norm = 1 / (1 + K / q + K * K)
+ a0 = (1 + K * K) * norm
+ a1 = 2 * (K * K - 1) * norm
+ a2 = a0
+ b1 = a1
+ b2 = (1 - K / q + K * K) * norm
+ break
+
+ case 'peak':
+ if (gain >= 0) {
+ norm = 1 / (1 + 1/q * K + K * K)
+ a0 = (1 + V/q * K + K * K) * norm
+ a1 = 2 * (K * K - 1) * norm
+ a2 = (1 - V/q * K + K * K) * norm
+ b1 = a1
+ b2 = (1 - 1/q * K + K * K) * norm
+ }
+ else {
+ norm = 1 / (1 + V/q * K + K * K)
+ a0 = (1 + 1/q * K + K * K) * norm
+ a1 = 2 * (K * K - 1) * norm
+ a2 = (1 - 1/q * K + K * K) * norm
+ b1 = a1
+ b2 = (1 - V/q * K + K * K) * norm
+ }
+ break
+ case 'lowshelf':
+ if (gain >= 0) {
+ norm = 1 / (1 + Math.SQRT2 * K + K * K)
+ a0 = (1 + Math.sqrt(2*V) * K + V * K * K) * norm
+ a1 = 2 * (V * K * K - 1) * norm
+ a2 = (1 - Math.sqrt(2*V) * K + V * K * K) * norm
+ b1 = 2 * (K * K - 1) * norm
+ b2 = (1 - Math.SQRT2 * K + K * K) * norm
+ }
+ else {
+ norm = 1 / (1 + Math.sqrt(2*V) * K + V * K * K)
+ a0 = (1 + Math.SQRT2 * K + K * K) * norm
+ a1 = 2 * (K * K - 1) * norm
+ a2 = (1 - Math.SQRT2 * K + K * K) * norm
+ b1 = 2 * (V * K * K - 1) * norm
+ b2 = (1 - Math.sqrt(2*V) * K + V * K * K) * norm
+ }
+ break
+ case 'highshelf':
+ if (gain >= 0) {
+ norm = 1 / (1 + Math.SQRT2 * K + K * K)
+ a0 = (V + Math.sqrt(2*V) * K + K * K) * norm
+ a1 = 2 * (K * K - V) * norm
+ a2 = (V - Math.sqrt(2*V) * K + K * K) * norm
+ b1 = 2 * (K * K - 1) * norm
+ b2 = (1 - Math.SQRT2 * K + K * K) * norm
+ }
+ else {
+ norm = 1 / (V + Math.sqrt(2*V) * K + K * K)
+ a0 = (1 + Math.SQRT2 * K + K * K) * norm
+ a1 = 2 * (K * K - 1) * norm
+ a2 = (1 - Math.SQRT2 * K + K * K) * norm
+ b1 = 2 * (K * K - V) * norm
+ b2 = (V - Math.sqrt(2*V) * K + K * K) * norm
+ }
+ break
+ }
+
+ for (var i = 0; i < len; i++) {
+
+ var w = mapToScale(frequencyHz[i], [0, Fs / 2], [0, Math.PI], -1, false),
+ phi = Math.pow(Math.sin(w / 2), 2),
+ y = Math.log(Math.pow(a0 + a1 + a2, 2) - 4 * (a0 * a1 + 4 * a0 * a2 + a1 * a2) * phi + 16 * a0 * a2 * phi * phi) -
+ Math.log(Math.pow(1 + b1 + b2, 2) - 4 * (b1 + 4 * b2 + b1 * b2) * phi + 16 * b2 * phi *phi)
+
+ y = y * 10 / Math.LN10
+
+ // if (y == -Infinity) y = -200
+
+ filterResponse[i] += y
+
+ }
+
+
+}
diff --git a/src/client/widgets/graphs/plot.js b/src/client/widgets/graphs/plot.js
new file mode 100644
index 00000000..a20467b0
--- /dev/null
+++ b/src/client/widgets/graphs/plot.js
@@ -0,0 +1,248 @@
+var {mapToScale} = require('../utils'),
+ Canvas = require('../common/canvas'),
+ html = require('nanohtml'),
+ StaticProperties = require('../mixins/static_properties')
+
+module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, interaction: false}) {
+
+ static description() {
+
+ return 'XY coordinates plot.'
+
+ }
+
+ static defaults() {
+
+
+ return super.defaults({
+
+ _class_specific: 'plot',
+
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (base 10). Set to a `number` to define the logarithm\'s base.'},
+ logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm\'s base.'},
+ origin: {type: 'number', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it.'},
+ dots: {type: 'boolean', value: false, help: 'Draw dots on the line'},
+ bars: {type: 'boolean', value: false, help: 'Set to `true` to use draw bars instead (disables `logScaleX` and forces `x axis` even spacing)'},
+ pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+
+ }, ['interaction', 'decimals', 'typeTags', 'bypass', 'ignoreDefaults'], {
+
+ value: {type: 'array|string', value: '', help: [
+ '- `Array` of `y` values',
+ '- `Array` of `[x, y]` `array` values',
+ '- `String` `array`',
+ '- `String` `object` to update specific coordinates only: `{0:1, 4:0}` will change the 1st and 5th points\' coordinates',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.value = []
+ this.rangeX = this.getProp('rangeX') || {min:0,max:1}
+ this.rangeY = this.getProp('rangeY') || {min:0,max:1}
+ this.logScaleX = this.getProp('logScaleX')
+ this.logScaleY = this.getProp('logScaleY')
+ this.pips = {
+ x : {
+ min: Math.abs(this.rangeX.min)>=1000?this.rangeX.min/1000+'k':this.rangeX.min,
+ max: Math.abs(this.rangeX.max)>=1000?this.rangeX.max/1000+'k':this.rangeX.max
+ },
+ y : {
+ min: Math.abs(this.rangeY.min)>=1000?this.rangeY.min/1000+'k':this.rangeY.min,
+ max: Math.abs(this.rangeY.max)>=1000?this.rangeY.max/1000+'k':this.rangeY.max
+ }
+ }
+
+ }
+
+ draw() {
+
+ this.ctx.clearRect(0,0,this.width,this.height)
+
+ if (this.getProp('bars')) {
+ this.draw_bars()
+ } else {
+ var points = this.draw_line()
+ if (this.getProp('dots')) {
+ this.draw_dots(points)
+ }
+ }
+
+ if (this.getProp('pips')) this.draw_pips()
+
+ }
+
+ draw_pips() {
+
+ this.ctx.fillStyle = this.cssVars.colorText
+ this.ctx.globalAlpha = this.cssVars.alphaPips
+
+ var margin = this.cssVars.padding + this.cssVars.lineWidth
+
+ if (margin < this.fontSize * 1.5) return
+
+
+ if (this.pips.x) {
+
+ this.ctx.textAlign = 'center'
+ this.ctx.fillText(this.pips.x.min, margin, this.height - margin / 2)
+ this.ctx.fillText(this.pips.x.max, this.width - margin, this.height - margin / 2)
+
+ }
+
+ if (this.pips.y) {
+
+ this.ctx.textAlign = 'right'
+ this.ctx.fillText(this.pips.y.min, margin / 2 + this.fontSize / 2, this.height - margin)
+ this.ctx.fillText(this.pips.y.max, margin / 2 + this.fontSize / 2, margin)
+
+ }
+
+ }
+
+ draw_line() {
+
+ var points = [],
+ padding = this.cssVars.padding + this.cssVars.lineWidth,
+ decimals = this.getProp('smooth') ? 1 : 0,
+ length = this.value.length,
+ x, y, i, previousValue, nx, ny
+
+ for (i = 0; i < length; i++) {
+
+ if (this.value[i].length) {
+ points.push(mapToScale(this.value[i][0], [this.rangeX.min, this.rangeX.max], [padding, this.width - padding], decimals, this.logScaleX, true))
+ points.push(mapToScale(this.value[i][1], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], decimals, this.logScaleY, true))
+ } else {
+
+ if (i < length - 2 && this.value[i] === previousValue && this.value[i+1] === previousValue) {
+ continue
+ }
+
+ nx = mapToScale(i, [0, this.value.length - 1], [padding, this.width - padding], decimals, this.logScaleX, true)
+ ny = mapToScale(this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], decimals, this.logScaleY, true)
+
+ if (x !== nx || y !== ny) {
+ points.push(nx)
+ points.push(ny)
+ x = nx
+ y = ny
+ }
+
+ previousValue = this.value[i]
+
+ }
+
+ }
+
+ if (points.length < 4) return points
+
+ this.ctx.beginPath()
+
+ this.ctx.moveTo(points[0], points[1])
+ for (i = 2; i < points.length - 2; i += 2) {
+ this.ctx.lineTo(points[i], points[i + 1])
+ }
+ this.ctx.lineTo(points[i], points[i + 1])
+
+ this.ctx.globalAlpha = 1
+ this.ctx.lineWidth = 2 * PXSCALE
+ this.ctx.strokeStyle = this.cssVars.colorWidget
+ this.ctx.stroke()
+
+ if (this.getProp('origin') !== false) {
+
+ var origin = mapToScale(this.getProp('origin'), [this.rangeY.min, this.rangeY.max], [this.height - padding, padding], 0, this.getProp('logScaleY'), true)
+
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.lineTo(this.width - padding, origin)
+ this.ctx.lineTo(padding, origin)
+ this.ctx.closePath()
+ this.ctx.fill()
+
+ }
+
+ return points
+
+ }
+
+ draw_dots(points) {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorWidget
+ this.ctx.strokeStyle = this.cssVars.colorBackground
+ this.ctx.lineWidth = 2 * PXSCALE
+ for (var i = 0; i < points.length; i += 2) {
+ this.ctx.beginPath()
+ this.ctx.arc(points[i], points[i + 1], 2 * PXSCALE, 0, 2*Math.PI)
+ this.ctx.fill()
+ this.ctx.stroke()
+ }
+
+ }
+
+ draw_bars() {
+
+ var barWidth = Math.round(this.width / this.value.length),
+ offset = Math.round((this.width - barWidth * this.value.length) / 2)
+
+ var origin = mapToScale(this.getProp('origin') !== false ? this.getProp('origin') : this.rangeY.min, [this.rangeY.min,this.rangeY.max],[this.height,0],0,this.getProp('logScaleY'),true)
+
+ this.ctx.beginPath()
+
+ for (let i in this.value) {
+ var y = mapToScale(this.value[i].length ? this.value[i][1] : this.value[i],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true)
+ this.ctx.rect(offset + i * barWidth, Math.min(y, origin), barWidth - PXSCALE, Math.abs(Math.min(y - origin)))
+
+ }
+
+ this.ctx.globalAlpha = 0.4
+ this.ctx.fillStyle = this.colors.custom
+ this.ctx.fill()
+
+ }
+
+ setValue(v, options={}) {
+
+ if (typeof v == 'string') {
+ try {
+ v = JSON.parseFlex(v)
+ } catch(err) {}
+ }
+
+ if (typeof v == 'object' && v !== null) {
+
+ if (Array.isArray(v)) {
+
+ this.value = v
+
+ } else {
+
+ for (var i in v) {
+ if (!isNaN(i)) this.value[i] = v[i]
+ }
+
+ }
+
+ this.batchDraw()
+
+ if (options.sync) this.changed(options)
+
+ }
+
+
+ }
+
+}
diff --git a/src/client/widgets/graphs/visualizer.js b/src/client/widgets/graphs/visualizer.js
new file mode 100644
index 00000000..e139259d
--- /dev/null
+++ b/src/client/widgets/graphs/visualizer.js
@@ -0,0 +1,162 @@
+var {clip} = require('../utils'),
+ Widget = require('../common/widget'),
+ Plot = require('./plot'),
+ StaticProperties = require('../mixins/static_properties'),
+ canvasQueue = require('../common/queue')
+
+
+class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dots: false, smooth: false, interaction: false}) {
+
+ static description() {
+
+ return 'Display its value over time.'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'visualizer',
+
+ duration: {type: 'number', value: 1, help: 'Defines visualization duration in seconds'},
+ framerate: {type: 'number', value: 30, help: 'Defines visualization framerate'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ origin: {type: 'number', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
+ logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm\'s base.'},
+ pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ freeze: {type: 'boolean', value: false, help: 'Set to `true` to freeze current view and ignore incoming values'}
+
+ }, ['interaction', 'decimals', 'typeTags', 'bypass', 'ignoreDefaults'], {})
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.fps = clip(this.getProp('framerate'), [1, CANVAS_FRAMERATE])
+ this.length = Math.round(clip(this.fps * this.getProp('duration'), [8, 4096]))
+ this.value = new Array(this.length).fill(this.rangeY.min)
+ this.cancel = false
+ this.looping = false
+ this.clock = 0
+ this.lastUpdate = 0
+ this.watchDuration = 1000 * this.getProp('duration')
+ this.ticks = 0
+
+ this.bindedLoop = this.loop.bind(this)
+
+ }
+
+ startLoop() {
+
+ this.clock = Date.now()
+ if (!this.looping && !this.getProp('freeze')) {
+ this.lastUpdate = Date.now()
+ canvasQueue.on('frame', this.bindedLoop)
+ if (!canvasQueue.running) canvasQueue.startLoop()
+ this.looping = true
+ this.ticks = 0
+ }
+ }
+
+ stopLoop() {
+
+ if (this.looping) {
+
+ canvasQueue.off('frame', this.bindedLoop)
+ this.looping = false
+
+ }
+
+ }
+
+ loop() {
+
+ var t = Date.now()
+
+ if (t - this.clock >= this.watchDuration) {
+ this.stopLoop()
+ }
+
+ this.ticks += (t - this.lastUpdate) / (1000 / this.fps)
+
+ if (Math.floor(this.ticks) > 0) {
+ this.shiftData(Math.floor(this.ticks))
+ this.ticks -= Math.floor(this.ticks)
+ this.batchDraw()
+ }
+
+ this.lastUpdate = t
+
+ }
+
+ shiftData(n) {
+
+ for (var i = 0; i < n; i++) {
+ this.value.push(this.value[this.length - 1])
+ this.value.splice(0,1)
+ }
+
+ }
+
+ getValue() {
+
+ return this.value[this.length - 1]
+
+ }
+
+ setValue(v, options={}) {
+
+
+ if (typeof(v) === 'number') {
+
+ this.value[this.length - 1] = v
+ this.startLoop()
+
+ if (options.sync) this.changed(options)
+
+
+ } else if (Array.isArray(v) && v.length === this.length) {
+
+ this.value = v
+ this.startLoop()
+
+ if (options.sync) this.changed(options)
+
+
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return
+
+ switch (propName) {
+
+ case 'freeze':
+ if (this.getProp('freeze')) this.stopLoop()
+ else this.startLoop()
+ return
+
+ }
+
+ }
+
+ onRemove() {
+
+ this.stopLoop()
+ super.onRemove()
+
+ }
+
+
+}
+
+Visualizer.dynamicProps = Visualizer.prototype.constructor.dynamicProps.concat(
+ 'freeze'
+)
+
+module.exports = Visualizer
diff --git a/src/client/widgets/index.js b/src/client/widgets/index.js
new file mode 100644
index 00000000..c201c795
--- /dev/null
+++ b/src/client/widgets/index.js
@@ -0,0 +1,70 @@
+module.exports.widgets = {
+
+ // basics
+ button: require('./basics/button'),
+ switch: require('./basics/switch'),
+ dropdown: require('./basics/dropdown'),
+ menu: require('./basics/menu'),
+ input: require('./basics/input'),
+ file: require('./basics/file'),
+
+ // containers
+ panel: require('./containers/panel'),
+ root: require('./containers/root'),
+ tab: require('./containers/tab'),
+ modal: require('./containers/modal'),
+ clone: require('./containers/clone'),
+ matrix: require('./containers/matrix'),
+ keyboard: require('./containers/keyboard'),
+ patchbay: require('./containers/patchbay').PatchBay,
+ patchbaynode: require('./containers/patchbay').PatchBayNode,
+
+ // frames
+ image: require('./frames/image'),
+ svg: require('./frames/svg'),
+ html: require('./frames/html'),
+ frame: require('./frames/frame'),
+
+ // graphs
+ plot: require('./graphs/plot'),
+ eq: require('./graphs/eq'),
+ visualizer: require('./graphs/visualizer'),
+
+ // indicators
+ led: require('./indicators/led'),
+ text: require('./indicators/text'),
+
+ // pads
+ xy: require('./pads/xy'),
+ rgb: require('./pads/rgb'),
+ multixy: require('./pads/multixy'),
+ canvas: require('./pads/canvas'),
+
+ // sliders
+ fader: require('./sliders/fader'),
+ knob: require('./sliders/knob'),
+ encoder: require('./sliders/encoder'),
+ range: require('./sliders/range'),
+
+ // scripts
+ script: require('./scripts/script'),
+ variable: require('./scripts/variable'),
+
+}
+
+module.exports.categories = {
+ 'Basics':['button', 'switch', 'dropdown', 'menu', 'input', 'file'],
+ 'Containers':['panel', 'modal', 'clone', 'matrix', 'keyboard', 'patchbay'],
+ 'Frames':['frame', 'svg', 'html', 'image'],
+ 'Graphs':['plot','eq','visualizer'],
+ 'Indicators':['led', 'text'],
+ 'Pads':['xy','rgb','multixy'],
+ 'Sliders':['fader','knob', 'encoder', 'range'],
+ 'Scripts':['script', 'variable'],
+}
+
+var defaults = {}
+for (var k in module.exports.widgets) {
+ defaults[k] = module.exports.widgets[k].defaults()
+}
+module.exports.defaults = defaults
diff --git a/src/client/widgets/indicators/led.js b/src/client/widgets/indicators/led.js
new file mode 100644
index 00000000..1aca0b1d
--- /dev/null
+++ b/src/client/widgets/indicators/led.js
@@ -0,0 +1,103 @@
+var {mapToScale} = require('../utils'),
+ Widget = require('../common/widget'),
+ html = require('nanohtml'),
+ StaticProperties = require('../mixins/static_properties')
+
+module.exports = class Led extends StaticProperties(Widget, {bypass: true, interaction: false}) {
+
+ static description() {
+
+ return 'Intensity display.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'led',
+
+ mode: {type: 'string', value: 'intensity', choices: ['intensity', 'color'], help: 'Defines how value is interpreted (see `value`)'},
+ range: {type: 'object', value: {min:0, max:1}, help: 'Value range'},
+ alphaRange: {type: 'object', value: {min:0, max:1}, help: 'Alpha range (if `mode` is `color`)'},
+ logScale: {type: 'boolean', value: false, help: 'If `mode` is `intensity`, set to `true` to use logarithmic scale.'},
+ borderRadius: {type: 'string', value: '', help: 'Css border-radius property.'},
+
+ }, ['interaction', 'decimals', 'bypass', 'ignoreDefaults'], {
+
+ value: {type: 'number|array|string', value: '', help: [
+ 'If `mode` is `intensity`:',
+ '- `Number`: `intensity` between `range.min` and `range.max`',
+ 'If `mode` is `color`:',
+ '- `Array`: `[r, g, b]` (`r`, `g` and `b` between `range.min` and `range.max`)',
+ '- `Array`: `[r, g, b, alpha]` (`alpha` between `alphaRange.min` and `alphaRange.max`)',
+ '- `String`: CSS color',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.setValueIntensity(this.getProp('mode') === 'intensity' ? this.getProp('range').min : this.getProp('range').max)
+
+ var bR = this.getProp('borderRadius')
+ if (parseInt(bR) == bR) bR += 'rem'
+ this.container.style.setProperty('--border-radius', bR)
+
+ }
+
+ setValue(v, options={}) {
+
+
+ var ret = this.getProp('mode') === 'intensity' ? this.setValueIntensity(v) : this.setValueColor(v)
+
+
+ if (options.sync && ret !== false) this.changed(options)
+
+ }
+
+ setValueIntensity(v) {
+
+ if (typeof v != 'number') return false
+
+ this.value = v
+ this.container.style.setProperty('--opacity', mapToScale(v, [this.getProp('range').min, this.getProp('range').max], [0, 1], -1, this.getProp('logScale'), true))
+
+
+ }
+
+ setValueColor(v) {
+
+ var c = ''
+
+ if (Array.isArray(v) && v.length >= 3) {
+
+ for (let i in [0, 1, 2]) {
+ v[i] = parseInt(mapToScale(v[i], [this.getProp('range').min, this.getProp('range').max], [0, 255]))
+ }
+
+ v[3] = v[3] === undefined ? 1 : mapToScale(v[3], [this.getProp('alphaRange').min, this.getProp('alphaRange').max], [0, 1], -1)
+
+ c = `rgba(${v[0]}, ${v[1]}, ${v[2]}, ${v[3]})`
+
+ } else if (typeof v == 'string') {
+
+ c = v
+
+ } else {
+
+ return false
+
+ }
+
+ this.value = v
+
+ this.container .style.setProperty('--color-led', c)
+
+ }
+
+}
diff --git a/src/client/widgets/indicators/text.js b/src/client/widgets/indicators/text.js
new file mode 100644
index 00000000..e919c774
--- /dev/null
+++ b/src/client/widgets/indicators/text.js
@@ -0,0 +1,62 @@
+var {iconify} = require('../../ui/utils'),
+ Widget = require('../common/widget'),
+ html = require('nanohtml'),
+ StaticProperties = require('../mixins/static_properties')
+
+module.exports = class Text extends StaticProperties(Widget, {bypass: true, interaction: false}) {
+
+ static description() {
+
+ return 'Display text.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'text',
+
+ vertical: {type: 'boolean', value: false, help: 'Set to `true` to display the text vertically'},
+ wrap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to wrap long lines automatically.',
+ ]},
+ align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Css text-align property.'},
+
+ }, ['interaction', 'decimals', 'bypass', 'ignoreDefaults'], {})
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.text = this.widget.appendChild(html` `)
+
+ if (this.getProp('vertical')) this.text.classList.add('vertical')
+ if (this.getProp('align') === 'left') this.text.classList.add('left')
+ if (this.getProp('align') === 'right') this.text.classList.add('right')
+ if (this.getProp('wrap')) this.text.classList.add('wrap')
+
+
+ this.setValue(this.getProp('default'))
+
+ }
+
+
+ setValue(v, options={}) {
+
+ this.value = v === '' || v === null ? this.getProp('default') : v
+
+ var s = String(this.value)
+ if (s.indexOf('^') > -1) {
+ this.text.innerHTML = iconify(s.replace(//g, '>').replace(/\n/g,' '))
+ } else {
+ this.text.textContent = s.replace(/\n/g,'\r\n')
+ }
+
+ if (options.sync) this.changed(options)
+
+ }
+
+}
diff --git a/src/client/widgets/mixins/double_tap.js b/src/client/widgets/mixins/double_tap.js
new file mode 100644
index 00000000..ac4c2287
--- /dev/null
+++ b/src/client/widgets/mixins/double_tap.js
@@ -0,0 +1,43 @@
+module.exports = (element, callback, options={})=>{
+
+ var lastTapTime = 0,
+ lastTapX,
+ lastTapY
+
+ element.addEventListener(options.click ? 'click' : 'fast-click', (event)=>{
+
+ if (event.capturedByEditor) return
+
+ var tapTime = Date.now(),
+ tapLength = tapTime - lastTapTime,
+ eventData = options.click ? event : event.detail
+
+ if (
+
+ tapLength < DOUBLE_TAP_TIME &&
+ Math.abs(lastTapX - eventData.pageX) < 20 &&
+ Math.abs(lastTapY - eventData.pageY) < 20 &&
+ (!options.click || event.pageX !== 0) // prevent fake click emitted with keyboard focus events
+
+ ) {
+
+ // execute callback at next cycle to ensure draginit events are resolved first
+ setTimeout(()=>{
+ callback(event.detail)
+ }, 0)
+ lastTapTime = 0
+
+ // prevent touchend
+ if (!options.click) event.detail.preventOriginalEvent = true
+
+ } else {
+
+ lastTapTime = tapTime
+ lastTapX = eventData.pageX
+ lastTapY = eventData.pageY
+
+ }
+
+ })
+
+}
diff --git a/src/client/widgets/mixins/static_properties.js b/src/client/widgets/mixins/static_properties.js
new file mode 100644
index 00000000..fc415dde
--- /dev/null
+++ b/src/client/widgets/mixins/static_properties.js
@@ -0,0 +1,16 @@
+let StaticProperties = (superclass, props) => class extends superclass {
+
+ createPropsCache() {
+
+ super.createPropsCache()
+
+ for (var k in props) {
+ this.cachedProps[k] = props[k]
+ }
+
+
+ }
+
+}
+
+module.exports = StaticProperties
diff --git a/src/browser/js/app/widgets/mixins/touch_state.js b/src/client/widgets/mixins/touch_state.js
similarity index 69%
rename from src/browser/js/app/widgets/mixins/touch_state.js
rename to src/client/widgets/mixins/touch_state.js
index 90b26224..ce3f857d 100644
--- a/src/browser/js/app/widgets/mixins/touch_state.js
+++ b/src/client/widgets/mixins/touch_state.js
@@ -1,11 +1,11 @@
-module.exports = (self, element)=>{
+module.exports = (self, options)=>{
var sendTouchState = self.getProp('touchAddress') && self.getProp('touchAddress').length
self.touched = 0
self.setValueTouchedQueue = undefined
- element.on('draginit',(e)=>{
+ self.on('draginit',(e)=>{
self.touched += 1
if (self.touched == 1 && sendTouchState)
self.sendValue({
@@ -13,9 +13,9 @@ module.exports = (self, element)=>{
v:1,
split:false
})
- })
+ }, options)
- element.on('dragend', (e, data, traversing)=>{
+ self.on('dragend', (e)=>{
if (self.touched == 1) {
self.touched = 0
@@ -34,8 +34,18 @@ module.exports = (self, element)=>{
} else if (self.touched > 1){
self.touched -= 1
- if (traversing) self.touched = 1
}
- })
+ }, options)
+
+ self.onRemove = ()=>{
+ if (sendTouchState && self.touched > 0) {
+ self.sendValue({
+ address:self.getProp('touchAddress'),
+ v:0,
+ split:false
+ })
+ }
+ self.__proto__.onRemove.call(self)
+ }
}
diff --git a/src/client/widgets/pads/canvas.js b/src/client/widgets/pads/canvas.js
new file mode 100644
index 00000000..6fc16004
--- /dev/null
+++ b/src/client/widgets/pads/canvas.js
@@ -0,0 +1,103 @@
+var Canvas = require('../common/canvas'),
+ html = require('nanohtml')
+
+class CanvasWidget extends Canvas {
+
+ static description() {
+
+ return 'KANVA !'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'canvas',
+
+
+ onCreate: {type: 'string', value: '', help: ' '},
+ onTouch: {type: 'string', value: '', help: ' '},
+
+ }, [], {})
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+
+ this.on('draginit',(e)=>{
+
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('drag',(e)=>{
+
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('dragend',(e)=>{
+
+
+ }, {element: this.widget, multitouch: true})
+
+
+ }
+
+ setValue(v, options={}) {
+
+ if (v === null || v === undefined || ((v.length || 1) !== this.getProp('valueLength'))) return
+
+ this.value = v
+
+ if (!options.dragged) {
+ var coords = this.resolveProp('valueToCoords', undefined, false, false, false, {
+ coords: this.touchCoords,
+ value: this.value,
+ width: this.width,
+ height: this.height,
+ local: this.localContext
+ }) || this.touchCoords
+
+ this.touchCoords = coords === undefined ? this.touchCoords : coords
+ }
+
+ this.batchDraw()
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+
+ draw() {
+
+ if (this.getProp('autoClear')) this.clear()
+
+ this.resolveProp('draw', undefined, false, false, false, {
+ ctx: this.ctx,
+ coords: this.touchCoords,
+ value: this.value,
+ colors: this.colors,
+ width: this.width,
+ height: this.height,
+ })
+
+
+ if (this.getProp('autoClear')) this.clearRect = [0, 0, this.width, this.height]
+
+ }
+
+
+}
+
+CanvasWidget.dynamicProps = CanvasWidget.prototype.constructor.dynamicProps.concat([
+])
+
+module.exports = CanvasWidget
diff --git a/src/client/widgets/pads/multixy.js b/src/client/widgets/pads/multixy.js
new file mode 100644
index 00000000..9491ebef
--- /dev/null
+++ b/src/client/widgets/pads/multixy.js
@@ -0,0 +1,307 @@
+var Pad = require('./pad'),
+ Xy = require('./xy'),
+ {clip} = require('../utils'),
+ touchstate = require('../mixins/touch_state')
+
+
+var xyDefaults = Xy.defaults()._props()
+
+
+module.exports = class MultiXy extends Pad {
+
+ static description() {
+
+ return 'Multi-point XY pad.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'multi xy',
+
+ points: {type: 'integer|array', value: 2, help: [
+ 'Defines the number of points on the pad',
+ 'Can be an array of strings that will be used as labels for the points (ex: `[\'A\', \'B\']`)'
+ ]},
+
+
+ _separator: 'xy',
+
+ pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
+ snap: {type: 'boolean', value: false, help: [
+ 'By default, the points are dragged from their initial position.',
+ 'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
+ pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale.'},
+ logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale.'},
+ sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.npoints = typeof this.getProp('points') == 'object' ? this.getProp('points').length : this.getProp('points')
+ this.labels = typeof this.getProp('points') == 'object'
+ this.pointSize = parseInt(this.getProp('pointSize'))
+
+ this.pads = []
+
+ for (let i = 0; i < this.npoints; i++) {
+ this.pads[i] = new Xy({props:{
+ ...xyDefaults,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ default:this.getProp('default').length === this.getProp('points') * 2 ? [this.getProp('default')[i*2], this.getProp('default')[i*2 + 1]] : '',
+ rangeX:this.getProp('rangeX'),
+ rangeY:this.getProp('rangeY'),
+ decimals:this.getProp('decimals'),
+ logScaleX:this.getProp('logScaleX'),
+ logScaleY:this.getProp('logScaleY'),
+ pointSize: this.getProp('pointSize'),
+ pips: this.getProp('pips') && i == this.npoints-1,
+ sensitivity: this.getProp('sensitivity'),
+ input:false
+ }, parent: this})
+ this.pads[i].canvas.classList.add('pad-' + i)
+ this.widget.append(this.pads[i].canvas)
+
+ }
+
+ this.value = []
+
+ this.padsCoords = []
+ this.touchMap = {}
+
+ touchstate(this, {element: this.widget, multitouch: true})
+
+ this.on('draginit',(e)=>{
+
+ var id
+
+ if (!this.touchMap[e.pointerId]) {
+
+ var ndiff, diff = -1
+
+ for (var i in this.pads) {
+
+ if (Object.values(this.touchMap).indexOf(i) != -1) continue
+
+ ndiff = Math.abs(e.offsetX - this.padsCoords[i][0]) + Math.abs(e.offsetY - (this.padsCoords[i][1] + this.height))
+
+ if (diff == -1 || ndiff < diff) {
+ id = i
+ diff = ndiff
+ }
+
+ }
+
+ this.touchMap[e.pointerId] = id
+
+
+ }
+
+ if (!id) return
+
+ e.stopPropagation = true
+
+ if (this.getProp('touchAddress')) {
+ this.sendValue({
+ address: this.getProp('touchAddress'),
+ v: [parseInt(id), 1],
+ })
+ }
+
+ this.pads[id].trigger('draginit', e)
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('drag',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+
+ if (!i) return
+
+ this.pads[i].trigger('drag', e)
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('dragend',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+
+ if (!i) return
+
+ e.stopPropagation = true
+
+ this.pads[i].trigger('dragend', e)
+
+ if (this.getProp('touchAddress')) {
+ this.sendValue({
+ address: this.getProp('touchAddress'),
+ v: [parseInt(this.touchMap[e.pointerId]), 0],
+ })
+ }
+
+ delete this.touchMap[e.pointerId]
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('change',(e)=>{
+ if (e.widget == this) return
+ e.stopPropagation = true
+ this.setValue(this.getValue(), e.options)
+ })
+
+ var v = []
+ for (let i = 0; i < this.npoints * 2; i = i + 2) {
+ [v[i],v[i+1]] = this.pads[i/2].getValue()
+ }
+
+ this.setValue(v)
+
+ }
+
+ resizeHandle(event){
+
+ super.resizeHandle(event)
+
+ for (var k in this.pads) {
+ this.pads[k].width = this.width
+ this.pads[k].height = this.height
+ this.pads[k].padPadding = this.padPadding
+ }
+
+ this.updateHandlesPosition()
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ super.cacheCanvasStyle(style)
+ for (var k in this.pads) {
+ this.pads[k].cacheCanvasStyle()
+ this.pads[k].batchDraw()
+ }
+
+ }
+
+ setVisibility() {
+
+ super.setVisibility()
+ for (var k in this.pads) {
+ this.pads[k].setVisibility()
+ }
+
+ }
+
+ updateHandlesPosition() {
+
+ for (var i=0;i
+
+
+ `})
+
+ this.canvas.style.setProperty('--pointSize', parseInt(this.getProp('pointSize')) + 'rem')
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ style = style || window.getComputedStyle(this.canvas)
+
+ super.cacheCanvasStyle(style)
+
+ this.pointSize = parseFloat(style.getPropertyValue('--pointSize')) * PXSCALE
+ this.padPadding = (this.cssVars.padding + this.cssVars.lineWidth) + 2 * PXSCALE
+
+ }
+
+}
+
+Pad.dynamicProps = Pad.prototype.constructor.dynamicProps.filter(n => n !== 'decimals')
+
+module.exports = Pad
diff --git a/src/client/widgets/pads/rgb.js b/src/client/widgets/pads/rgb.js
new file mode 100644
index 00000000..025f20a2
--- /dev/null
+++ b/src/client/widgets/pads/rgb.js
@@ -0,0 +1,307 @@
+var Widget = require('../common/widget'),
+ Xy = require('./xy'),
+ Fader = require('../sliders/fader'),
+ {clip, mapToScale, hsbToRgb, rgbToHsb} = require('../utils'),
+ html = require('nanohtml')
+
+var faderDefaults = Fader.defaults()._props(),
+ xyDefaults = Xy.defaults()._props()
+
+
+module.exports = class Rgb extends Widget {
+
+ static description() {
+
+ return 'Color picker with optional alpha slider.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'rgb',
+
+ snap: {type: 'boolean', value: false, help: [
+ 'By default, the points are dragged from their initial position.',
+ 'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
+ range: {type: 'object', value: {min: 0, max: 255}, help: 'Defines the widget\'s output scale.'},
+ alpha:{type: 'boolean', value: false, help: 'Set to `true` to enable alpha channel'},
+ rangeAlpha: {type: 'object', value: {min: 0, max: 1}, help: 'Defines the widget\'s output scale for the alpha channel.'},
+
+ }, ['color'], {
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.container.classList.toggle('contains-alpha', this.getProp('alpha'))
+
+ this.pad = new Xy({props:{
+ ...xyDefaults,
+ type: 'xy',
+ label: false,
+ snap:this.getProp('snap'),
+ rangeX:{min:0,max:100},
+ rangeY:{min:0,max:100},
+ decimals:2,
+ pointSize: 10,
+ pips: false,
+ }, parent: this})
+ this.pad.sendValue = ()=>{}
+ this.pad.container.classList.add('not-editable', 'pad')
+ this.widget.appendChild(this.pad.container)
+ this.pad.on('change',(e)=>{
+ e.stopPropagation = true
+ this.dragHandle()
+ })
+
+ this.hue = new HueFader({props:{
+ ...faderDefaults,
+ type: 'fader',
+ design: 'compact',
+ label: false,
+ pips:false,
+ horizontal:false,
+ snap:this.getProp('snap'),
+ range:{min:0,max:360},
+ decimals:2
+ }, parent: this})
+ this.hue.container.classList.add('not-editable', 'hue')
+ this.widget.appendChild(this.hue.container)
+ this.hue.on('change',(e)=>{
+ e.stopPropagation = true
+ this.dragHandle(true)
+ })
+
+ if (this.getProp('alpha')) {
+ this.alpha = new Fader({props:{
+ ...faderDefaults,
+ type: 'fader',
+ design: 'compact',
+ label:false,
+ pips:false,
+ horizontal:true,
+ snap:this.getProp('snap'),
+ range: this.getProp('rangeAlpha'),
+ default: 255,
+ input:false,
+ decimals:2
+ }, parent: this})
+ this.alpha.container.classList.add('not-editable', 'alpha')
+ this.widget.appendChild(this.alpha.container)
+ this.alpha.on('change',(e)=>{
+ e.stopPropagation = true
+ this.dragAlphaHandle()
+ })
+ }
+
+ var initValue = Array.isArray(this.getProp('default')) && this.getProp('default').length >= 3 ? this.getProp('default') : Array(3).fill(this.getProp('range').min)
+ if (this.getProp('alpha') && initValue.length < 4) {
+ initValue[3] = this.getProp('rangeAlpha').min
+ }
+
+ if (this.getProp('spring')) {
+
+ this.on('dragend', (e)=>{
+
+ e.stopPropagation = true
+ this.setValue(initValue, {sync:true,send:true})
+
+ }, {element: this.widget, ignoreCustomBindings: true})
+
+ }
+
+
+ this.value = []
+
+ this.hsb = {h:0,s:0,b:0}
+
+ this.setValue(initValue)
+
+ }
+
+ dragHandle(hue) {
+ var h = this.hue.value,
+ s = this.pad.value[0],
+ b = this.pad.value[1]
+
+ if (h != this.hsb.h ||s != this.hsb.s || b != this.hsb.b) {
+
+ this.hsb.h = this.hue.value
+ this.hsb.s = this.pad.value[0]
+ this.hsb.b = this.pad.value[1]
+
+ this.update({nohue:!hue})
+
+ var rgb = hsbToRgb(this.hsb)
+ for (var k in rgb) {
+ rgb[k] = mapToScale(rgb[k], [0, 255], [this.getProp('range').min, this.getProp('range').max], -1)
+ }
+
+ if (rgb.r != this.value[0] || rgb.g != this.value[1] || rgb.b != this.value[2]) {
+ this.setValue([rgb.r, rgb.g, rgb.b], {
+ send: true,
+ sync: true,
+ dragged: true,
+ nohue: !hue
+ })
+ }
+ }
+
+ }
+
+ dragAlphaHandle() {
+
+ var alpha = this.alpha.value
+ if (alpha !== this.value[3]) {
+ this.setValue([this.value[0], this.value[1], this.value[2], alpha], {
+ send: true,
+ sync: true,
+ dragged: true,
+ nohue: true
+ })
+ }
+
+
+ }
+
+ setValue(v, options={}) {
+
+ if (!v || v.length < 3) return
+ if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
+
+ var value = Array(this.getProp('alpha') ? 4 : 3)
+
+ for (var i = 0; i < 3; i++) {
+ value[i] = clip(v[i], [this.getProp('range').min, this.getProp('range').max])
+ }
+
+ if (value.length === 4) {
+ value[3] = v[3] === undefined ? this.alpha.value : clip(v[3], [this.getProp('rangeAlpha').min, this.getProp('rangeAlpha').max])
+ }
+
+ var hsb = rgbToHsb({
+ r: mapToScale(value[0], [this.getProp('range').min, this.getProp('range').max], [0, 255], -1),
+ g: mapToScale(value[1], [this.getProp('range').min, this.getProp('range').max], [0, 255], -1),
+ b: mapToScale(value[2], [this.getProp('range').min, this.getProp('range').max], [0, 255], -1)
+ })
+
+ if (!options.dragged) {
+ this.pad.setValue([hsb.s, hsb.b])
+ if (value.length === 4) this.alpha.setValue(value[3])
+ }
+
+ this.hsb = hsb
+ this.value = value
+
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.update({dragged:options.dragged, nohue:options.nohue || (v[0]==v[1]&&v[1]==v[2])})
+
+ }
+
+ update(options={}) {
+
+ if (!options.nohue && !options.dragged) {
+ var hue = hsbToRgb({h:this.hsb.h,s:100,b:100}),
+ hueStr = `rgb(${Math.round(hue.r)},${Math.round(hue.g)},${Math.round(hue.b)})`
+ this.pad.container.setAttribute('style',`background-color:${hueStr}`)
+ this.hue.setValue(this.hsb.h, {sync: false, send:false, dragged:false})
+ }
+
+ }
+
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ for (var w of [this.hue, this.pad]) {
+ w.onPropChanged(propName)
+ }
+ if (this.alpha) this.alpha.onPropChanged(propName)
+ return
+
+ }
+
+ }
+
+ setVisibility() {
+
+ super.setVisibility()
+
+ for (var w of [this.hue, this.pad]) {
+ if (w) w.setVisibility()
+ }
+ if (this.alpha) this.alpha.setVisibility()
+
+ }
+
+ onRemove() {
+ this.hue.onRemove()
+ this.pad.onRemove()
+ if (this.alpha) this.alpha.onRemove()
+ super.onRemove()
+ }
+
+}
+
+class HueFader extends Fader {
+
+ draw() {
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width
+
+ var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
+ d = Math.round(this.percentToCoord(percent)),
+ m = this.getProp('horizontal') ? this.height / 2 : this.width / 2,
+ flat = this.getProp('mode') === 'flat'
+
+ // sharp border trick
+ if (width % 2 && parseInt(m) === m) m -= 0.5
+
+ this.clear()
+
+
+ this.ctx.strokeStyle = this.gaugeGradient || this.cssVars.colorFill
+
+ if (flat) {
+ this.ctx.lineWidth = Math.round(width - this.gaugePadding * 2)
+ } else {
+ this.ctx.lineWidth = 2 * PXSCALE
+ }
+
+
+ // flat knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorFill
+
+ this.ctx.beginPath()
+ this.ctx.rect(this.gaugePadding, Math.min(d, height - 2 * PXSCALE), width - this.gaugePadding * 2, 2 * PXSCALE)
+ this.ctx.fill()
+
+ this.clearRect = [0, 0, width, height]
+
+ }
+
+}
diff --git a/src/client/widgets/pads/xy.js b/src/client/widgets/pads/xy.js
new file mode 100644
index 00000000..b8accd9b
--- /dev/null
+++ b/src/client/widgets/pads/xy.js
@@ -0,0 +1,287 @@
+var Pad = require('./pad'),
+ Fader = require('../sliders/fader'),
+ doubletab = require('../mixins/double_tap'),
+ touchstate = require('../mixins/touch_state')
+
+var faderDefaults = Fader.defaults()._props()
+
+module.exports = class Xy extends Pad {
+
+ static description() {
+
+ return 'Two-dimensional slider.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'xy',
+
+ pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
+ snap: {type: 'boolean', value: false, help: [
+ 'By default, the points are dragged from their initial position.',
+ 'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
+ pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale.'},
+ logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale.'},
+ doubleTap: {type: 'boolean|string', value: false, help: [
+ 'Set to `true` to make the fader reset to its default value when receiving a double tap.',
+ 'Can also be an osc address, which case the widget will just send an osc message: `/ `'
+ ]},
+ sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`)'},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.faders = {
+ x: new Fader({props:{
+ ...faderDefaults,
+ id:0,
+ visible:false,
+ horizontal:true,
+ default:this.getProp('default').length === 2 ? this.getProp('default')[0] : '',
+ snap:this.getProp('snap'),
+ range:this.getProp('rangeX'),
+ decimals:this.getProp('decimals'),
+ logScale:this.getProp('logScaleX'),
+ sensitivity: this.getProp('sensitivity'),
+ }, parent: this}),
+ y: new Fader({props:{
+ ...faderDefaults,
+ id:1,
+ visible:false,
+ horizontal:false,
+ default:this.getProp('default').length === 2 ? this.getProp('default')[1] : '',
+ snap:this.getProp('snap'),
+ range:this.getProp('rangeY'),
+ decimals:this.getProp('decimals'),
+ logScale:this.getProp('logScaleY'),
+ sensitivity: this.getProp('sensitivity'),
+ }, parent: this}),
+ }
+
+ this.on('change',(e)=>{
+ if (e.widget == this) return
+ e.stopPropagation = true
+ })
+
+ this.value = []
+
+ touchstate(this, {element: this.canvas})
+
+ this.active = false
+
+ this.on('draginit',(e)=>{
+ this.active = true
+ this.faders.x.trigger('draginit', {...e, stopPropagation: true})
+ this.faders.y.trigger('draginit', {...e, stopPropagation: true})
+ this.dragHandle()
+ }, {element: this.canvas})
+
+ this.on('drag',(e)=>{
+ this.faders.x.trigger('drag', e)
+ this.faders.y.trigger('drag', e)
+ this.dragHandle()
+ }, {element: this.canvas})
+
+ this.on('dragend', (e)=>{
+ this.active = false
+ this.faders.x.trigger('dragend', {...e, stopPropagation: true})
+ this.faders.y.trigger('dragend', {...e, stopPropagation: true})
+ if (this.getProp('spring')) {
+ this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true,send:true})
+ } else {
+ this.batchDraw()
+ }
+ }, {element: this.canvas})
+
+ if (this.getProp('doubleTap')) {
+
+ if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
+
+ doubletab(this.widget, ()=>{
+ this.sendValue({v:null, address: this.getProp('doubleTap')})
+ })
+
+ } else {
+
+ doubletab(this.widget, ()=>{
+ this.faders.x.setValue(this.faders.x.getSpringValue(), {sync: false, send:false, dragged:true})
+ this.faders.y.setValue(this.faders.y.getSpringValue(), {sync: false, send:false, dragged:true})
+ this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true, send:true})
+ })
+
+ }
+
+ }
+
+ this.setValue([0,0])
+
+ }
+
+ dragHandle(){
+
+ var x = this.faders.x.value,
+ y = this.faders.y.value
+
+
+ if (x != this.value[0] || y != this.value[1]) {
+ this.setValue([x, y],{send:true,sync:true,dragged:true})
+ } else {
+ this.batchDraw()
+ }
+
+ }
+
+ resizeHandle(event){
+
+ super.resizeHandle(event)
+
+ for (var k in this.faders) {
+ this.faders[k].width = this.width
+ this.faders[k].height = this.height
+ this.faders[k].gaugePadding = this.padPadding
+
+ }
+
+ }
+
+
+ setValue(v, options={}) {
+
+ if (!v || !v.length || v.length!=2) return
+ if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
+
+ if (!options.dragged) {
+ this.faders.x.setValue(v[0], {sync: false, send:false, dragged:false})
+ this.faders.y.setValue(v[1], {sync: false, send:false, dragged:false})
+ }
+
+ this.value = [
+ this.faders.x.value,
+ this.faders.y.value
+ ]
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.batchDraw()
+
+ }
+
+ draw() {
+
+ var pointSize = this.pointSize,
+ margin = this.padPadding,
+ x = this.faders.x.percentToCoord(this.faders.x.percent),
+ y = this.faders.y.percentToCoord(this.faders.y.percent)
+
+ this.clear()
+
+
+ this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(x, y, pointSize - 3 * PXSCALE, Math.PI * 2, false)
+ this.ctx.fill()
+
+
+
+
+ var pipsDrawn = false
+ if (this.getProp('pips')) {
+
+ var pipTexts = margin >= this.fontSize * 1.5
+
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.fillStyle = this.cssVars.colorText
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.globalAlpha = this.cssVars.alphaPips
+ this.ctx.beginPath()
+
+ for (let i in this.faders.x.rangeKeys) {
+
+ let pip = this.faders.x.rangeKeys[i],
+ px = Math.round(0.5 * this.faders.x.percentToCoord(pip)) * 2
+
+ if (parseInt(px) === px) px -= 0.5
+
+ if (pipTexts) {
+ this.ctx.textAlign = 'center'
+ let label = this.faders.x.rangeLabels[i]
+ this.ctx.fillText(label, px, this.height - margin / 2)
+ pipsDrawn = true
+ }
+
+ if (pip == 0 || pip == 100) continue
+ this.ctx.moveTo(px, margin - PXSCALE)
+ this.ctx.lineTo(px, this.height - margin + PXSCALE)
+ pipsDrawn = true
+
+
+ }
+ for (let i in this.faders.y.rangeKeys) {
+
+ let pip = this.faders.y.rangeKeys[i],
+ py = Math.round(0.5 * this.faders.y.percentToCoord(pip)) * 2
+
+ if (parseInt(py) === py) py -= 0.5
+
+ if (pipTexts) {
+ this.ctx.textAlign = 'right'
+ let label = this.faders.y.rangeLabels[i]
+ this.ctx.fillText(label, margin / 2 + this.fontSize / 2, py)
+ pipsDrawn = true
+ }
+
+ if (pip == 0 || pip == 100) continue
+ this.ctx.moveTo(margin - PXSCALE, py)
+ this.ctx.lineTo(this.width - margin + PXSCALE, py)
+ pipsDrawn = true
+
+
+ }
+
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.stroke()
+
+ }
+
+ if (!pipsDrawn) this.clearRect = [x - this.pointSize - 2 * PXSCALE, y - this.pointSize - 2 * PXSCALE, (this.pointSize + PXSCALE) * 4, (this.pointSize + PXSCALE) * 4]
+
+
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.globalAlpha = this.active ? 1 : 0.75
+ this.ctx.lineWidth = 1.5 * PXSCALE
+ this.ctx.beginPath()
+ this.ctx.arc(x, y, pointSize, Math.PI * 2, false)
+ this.ctx.stroke()
+
+
+
+ }
+
+ onRemove() {
+
+ this.faders.x.onRemove()
+ this.faders.y.onRemove()
+ super.onRemove()
+
+ }
+
+}
diff --git a/src/client/widgets/scripts/gyro-archive.js b/src/client/widgets/scripts/gyro-archive.js
new file mode 100644
index 00000000..b3baa851
--- /dev/null
+++ b/src/client/widgets/scripts/gyro-archive.js
@@ -0,0 +1,125 @@
+var Widget = require('../common/widget'),
+ GyroNorm = require('gyronorm/dist/gyronorm.complete.min.js'),
+ {icon} = require('../../ui/utils'),
+ {clip} = require('../utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+
+class Gyroscope extends Widget {
+
+ static description() {
+
+ return 'Device motion/orientation sensor.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'gyroscope',
+
+ frequency: {type: 'number', value: 30, help: 'Value update frequency (updates per seconds)'},
+ normalize: {type: 'boolean', value: true, help: 'Normalize gravity related values'},
+ compass: {type: 'boolean', value: false, help: 'Set to `true` to return the orientation values with respect to the actual north direction of the world instead of the head direction of the device'},
+ screenAdjusted: {type: 'boolean', value: false, help: 'Set to `true` to return screen adjusted values'}
+
+ }, [], {
+
+ value: {type: 'object', value: '', help: [
+ 'The gyroscope\'s value is an object containing multiple values, which can be used by other widgets via the property maths syntax',
+ '- `value.do.alpha`: deviceorientation event alpha',
+ '- `value.do.beta`: deviceorientation event beta',
+ '- `value.do.gamma`: deviceorientation event gamma',
+ '- `value.do.absolute`: deviceorientation event absolute',
+ '- `value.dm.x`: devicemotion event acceleration x',
+ '- `value.dm.y`: devicemotion event acceleration y',
+ '- `value.dm.z`: devicemotion event acceleration z',
+ '- `value.dm.gx`: devicemotion event accelerationIncludingGravity x',
+ '- `value.dm.gy`: devicemotion event accelerationIncludingGravity y',
+ '- `value.dm.gz`: devicemotion event accelerationIncludingGravity z',
+ '- `value.dm.alpha`: devicemotion event rotationRate alpha',
+ '- `value.dm.beta`: devicemotion event rotationRate beta',
+ '- `value.dm.gamma`: devicemotion event rotationRate gamma'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ ${raw(icon('compass'))}
+
+ `})
+
+ this.sensor = new GyroNorm()
+ this.sensor.init({
+
+ frequency: 1000 / clip(this.getProp('frequency'), [0.01, 60]),
+ gravityNormalized: this.getProp('normalize'),
+ orientationBase: this.getProp('compass') ? GyroNorm.WORLD : GyroNorm.GAME,
+ decimalCount: this.getProp('decimals'),
+ screenAdjusted: this.getProp('screenAdjusted'),
+ logger: null
+
+ }).then(()=>{
+
+ this.sensor.start((data)=>{
+
+ this.setValue(data, {sync: true, send: true})
+
+ // data.do.alpha ( deviceorientation event alpha value )
+ // data.do.beta ( deviceorientation event beta value )
+ // data.do.gamma ( deviceorientation event gamma value )
+ // data.do.absolute ( deviceorientation event absolute value )
+
+ // data.dm.x ( devicemotion event acceleration x value )
+ // data.dm.y ( devicemotion event acceleration y value )
+ // data.dm.z ( devicemotion event acceleration z value )
+
+ // data.dm.gx ( devicemotion event accelerationIncludingGravity x value )
+ // data.dm.gy ( devicemotion event accelerationIncludingGravity y value )
+ // data.dm.gz ( devicemotion event accelerationIncludingGravity z value )
+
+ // data.dm.alpha ( devicemotion event rotationRate alpha value )
+ // data.dm.beta ( devicemotion event rotationRate beta value )
+ // data.dm.gamma ( devicemotion event rotationRate gamma value )
+
+
+ })
+
+ }).catch((e)=>{
+
+ console.log(e)
+
+ })
+
+ }
+
+
+
+ setValue(v, options={} ) {
+
+ this.value = v
+
+ // if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ onRemove() {
+
+ this.sensor.end()
+
+ super.onRemove()
+
+ }
+
+
+}
+
+module.exports = Gyroscope
diff --git a/src/client/widgets/scripts/script-vm.js b/src/client/widgets/scripts/script-vm.js
new file mode 100644
index 00000000..0c1a1452
--- /dev/null
+++ b/src/client/widgets/scripts/script-vm.js
@@ -0,0 +1,345 @@
+var widgetManager = require('../../managers/widgets'),
+ stateManager = require('../../managers/state'),
+ cache = require('../../managers/cache'),
+ {deepCopy} = require('../../utils'),
+ {urlParser} = require('../utils'),
+ Vm = require('../vm'),
+ toolbar
+
+
+class ScriptVm extends Vm {
+
+ constructor() {
+
+ super()
+
+ this.valueOptions = []
+ this.widget = []
+
+ }
+
+ getValueOptions() {
+
+ return this.valueOptions[this.valueOptions.length - 1] || {send: true, sync: true}
+
+ }
+
+ setValueOptions(options) {
+
+ if (!options) this.valueOptions.pop()
+ else this.valueOptions.push(options)
+
+ }
+
+ setWidget(widget) {
+
+ if (!widget) this.widget.pop()
+ else this.widget.push(widget)
+
+ }
+
+ getWidget() {
+
+ return this.widget[this.widget.length - 1]
+
+ }
+
+ resolveId(id) {
+
+ var widget = this.getWidget()
+ if (widget.builtIn) widget = widget.parent
+
+ if (id === 'this') return [widget]
+ else if (id === 'parent' && widget.parent !== widgetManager) return [widget.parent]
+ else return widgetManager.getWidgetById(id)
+
+ }
+
+ registerGlobals() {
+
+ super.registerGlobals()
+
+ this.sandbox.contentWindow.set = (id, value)=>{
+
+ var options = this.getValueOptions()
+ options.fromScript = true
+
+ // if (id === options.id) options.sync = false // loop stop
+ // if (this.getWidget() === options.widget) options.sync = false // loop stop
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ return widgets[i].setValue(value, options)
+
+ }
+
+ }
+
+ this.sandbox.contentWindow.send = (target, address, ...args)=>{
+
+ var options = this.getValueOptions()
+
+ if (!options.send) return
+
+ if (target && target[0] === '/') {
+ args.unshift(address)
+ address = target
+ target = null
+ }
+
+ var overrides = {
+ address,
+ v: args,
+ preArgs: []
+ }
+
+ if (target) overrides.target = Array.isArray(target) ? target : [target]
+
+ var widget = this.getWidget()
+ if (widget.builtIn) widget = widget.parent
+
+ widget.sendValue(overrides)
+
+ }
+
+ this.sandbox.contentWindow.get = (id)=>{
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].getValue) {
+
+ var v = widgets[i].getValue()
+ if (v !== undefined) return v
+
+ }
+
+ }
+
+ }
+
+ this.sandbox.contentWindow.getProp = (id, prop)=>{
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ var v = widgets[i].getProp(prop)
+ if (v !== undefined) return v
+
+ }
+
+ }
+
+ this.sandbox.contentWindow.updateProp = (id, prop)=>{
+
+ var widgets = this.resolveId(id),
+ widget = this.getWidget()
+
+ if (widget.builtIn) widget = widget.parent
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ widgets[i].updateProps(Array.isArray(prop) ? prop : [prop], widget)
+
+ }
+
+ }
+
+ this.sandbox.contentWindow.getScroll = (id)=>{
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].scroll) return widgets[i].scroll()
+
+ }
+
+ return []
+
+ }
+
+ this.sandbox.contentWindow.setScroll = (id, x, y)=>{
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].scroll) widgets[i].scroll([x, y])
+
+ }
+
+ }
+
+ this.sandbox.contentWindow.httpGet = (url, callback)=>{
+
+ var parser = urlParser(url),
+ err = (e)=>{console.error(e)}
+
+ if (!parser.isLocal()) return err('httpGet error (' + url + '): non-local url')
+
+ var xhr = new XMLHttpRequest()
+ xhr.open('GET', url, true)
+ xhr.onload = (e)=>{
+ if (xhr.readyState === 4 && xhr.status === 200 && callback) {
+ callback(xhr.responseText)
+ }
+ }
+ xhr.onerror = (e)=>err('httpGet error (' + url + '): ' + xhr.statusText)
+ xhr.send(null)
+
+ }
+
+ this.sandbox.contentWindow.stateGet = (filter)=>{
+
+ if (filter) {
+
+ filter = Array.isArray(filter) ? filter : [filter]
+
+ var containers = filter.map(x=>this.resolveId(x)).reduce((a,b)=>a.concat(b), [])
+
+ if (!containers.length) return
+ filter = (widget)=>{
+ return containers.some(x=>x.contains(widget) || x === widget)
+ }
+ }
+
+ return deepCopy(stateManager.get(filter))
+
+ }
+
+ this.sandbox.contentWindow.stateSet = (state)=>{
+
+ var options = this.getValueOptions()
+ stateManager.set(state, options.send)
+
+ }
+
+
+ this.sandbox.contentWindow.storage = {
+
+ setItem: (k, v)=>cache.set('script.' + k, v),
+ getItem: (k)=>cache.get('script.' + k),
+ removeItem: (k)=>cache.remove('script.' + k),
+ clear: ()=>cache.clear('script.')
+
+ }
+
+ this.sandbox.contentWindow.setTimeout = (id, callback, timeout)=>{
+
+ if (typeof id === 'function') {
+ timeout = callback
+ callback = id
+ id = undefined
+ }
+
+ var widget = this.getWidget(),
+ options = this.getValueOptions()
+
+
+ if (widget.timeouts[id] !== undefined) {
+ clearTimeout(widget.timeouts[id])
+ delete widget.timeouts[id]
+ }
+ widget.timeouts[id] = setTimeout(()=>{
+ this.setWidget(widget)
+ this.setValueOptions(options)
+ try {
+ callback()
+ } catch(e) {
+ console.log(e)
+ }
+ this.setWidget()
+ this.setValueOptions()
+ }, timeout)
+
+ }
+
+ this.sandbox.contentWindow.clearTimeout = (id)=>{
+
+ var widget = this.getWidget()
+
+ clearTimeout(widget.timeouts[id])
+ delete widget.timeouts[id]
+
+ }
+
+ this.sandbox.contentWindow.setInterval = (id, callback, timeout)=>{
+
+ if (typeof id === 'function') {
+ timeout = callback
+ callback = id
+ id = undefined
+ }
+
+ var widget = this.getWidget(),
+ options = this.getValueOptions()
+
+
+ if (widget.intervals[id] !== undefined) clearTimeout(widget.intervals[id])
+ delete widget.intervals[id]
+
+ widget.intervals[id] = setInterval(()=>{
+ this.setWidget(widget)
+ this.setValueOptions(options)
+ try {
+ callback()
+ } catch(e) {
+ console.log(e)
+ }
+ this.setWidget()
+ this.setValueOptions()
+ }, timeout)
+
+ }
+
+ this.sandbox.contentWindow.clearInterval = (id)=>{
+
+ var widget = this.getWidget()
+
+ clearInterval(widget.intervals[id])
+ delete widget.intervals[id]
+
+ }
+
+ this.sandbox.contentWindow.unfocus = ()=>{
+
+ // built-in client only: electron will call window.blur()
+ console.debug('ELECTRON.BLUR()')
+
+ }
+
+ this.sandbox.contentWindow.toolbar = (...args)=>{
+
+ var options = this.getValueOptions()
+
+ if (!options.send) return
+
+ toolbar = toolbar || require('../../ui/ui-toolbar')
+
+ var action = toolbar.entries.filter(x=>!x.separator)
+
+ for (var i of args) {
+ if (action[i]) action = action[i].action
+ if (!Array.isArray(action)) break
+ action = action.filter(x=>!x.separator)
+ }
+
+ if (typeof action === 'function') action()
+
+ }
+
+ for (var imports of ['set', 'get', 'getProp', 'updateProp', 'send', 'httpGet', 'stateGet', 'stateSet', 'storage',
+ 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'unfocus', 'setScroll', 'getScroll', 'toolbar']) {
+ this.sanitize(this.sandbox.contentWindow[imports])
+ }
+
+ }
+
+}
+
+module.exports = ScriptVm
diff --git a/src/client/widgets/scripts/script.js b/src/client/widgets/scripts/script.js
new file mode 100644
index 00000000..41f9ce5b
--- /dev/null
+++ b/src/client/widgets/scripts/script.js
@@ -0,0 +1,186 @@
+var Widget = require('../common/widget'),
+ keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
+ ScriptVm = require('./script-vm'),
+ scriptVm = new ScriptVm()
+
+
+class Script extends Widget {
+
+ static description() {
+
+ return 'Evaluates a script each time it receives a value.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'script',
+
+ event: {type: 'string', value: 'value', choices: ['value', 'keyboard'], help: 'Define which events trigger the script\'s execution.'},
+ script: {},
+
+ _separator: 'event: keyboard',
+
+ keyBinding: {type: 'string|array', value: '', help: 'Key combo `string` or `array` of strings (see KeyboardJS documentation)'},
+ keyRepeat: {type: 'boolean', value: true, help: 'Set to `false` to prevent keydown repeats when holding the key combo pressed'},
+ keyType: {type: 'string', value: 'keydown', choices: ['keydown', 'keyup', 'both'], help: 'Determines which key event trigger the script\'s execution'},
+
+
+
+ }, [
+
+ 'visible', 'interaction',
+ '_geometry', 'left', 'top', 'width', 'height', 'expand',
+ '_style', 'colorBg', 'colorText', 'colorWidget', 'colorFill', 'colorStroke', 'alphaStroke', 'alphaFillOn', 'alphaFillOff', 'padding', 'css'
+
+ ], {
+ script: {type: 'script', value: '', help: 'Script executed whenever the widget\'s receives the defined event. See documentation .'},
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: null})
+
+ this.builtIn = options.builtIn
+
+ this.scriptLock = false
+
+ this.timeouts = {}
+ this.intervals = {}
+
+ if (this.getProp('event') === 'value') {
+
+ try {
+ this.script = scriptVm.compile(this.getProp('script'), {
+ id: '',
+ value: 0
+ })
+ } catch(err) {
+ let stackline = err.stack ? (err.stack.match(/>:([0-9]+):[0-9]+/) || '') : '',
+ line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - 2) : ''
+ console.log((this.getProp('id') || this.props.id) + '.script error:\n' + err + line)
+ this.script = ()=>{}
+ }
+
+ } else if (this.getProp('event') === 'keyboard' && this.getProp('keyBinding')) {
+
+ this.keyCb = this.keyboardCallback.bind(this)
+
+ keyboardJS.withContext('global', ()=>{
+
+ keyboardJS.bind(this.getProp('keyBinding'), this.keyCb, this.keyCb)
+
+ })
+
+ try {
+ this.script = scriptVm.compile(this.getProp('script'), {
+ type: '',
+ key: '',
+ code: 0,
+ ctrl: false,
+ shift: false,
+ alt: false,
+ meta: false,
+ })
+ } catch(err) {
+ let stackline = err.stack ? (err.stack.match(/>:([0-9]+):[0-9]+/) || '') : '',
+ line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - 2) : ''
+ console.log((this.getProp('id') || this.props.id) + '.script error:\n' + err + line)
+ this.script = ()=>{}
+ }
+
+ }
+
+ }
+
+ run(context) {
+
+ if (this.scriptLock) return
+
+ scriptVm.setWidget(this)
+
+ this.scriptLock = true
+ try {
+ this.script(context, this.builtIn ? this.parent.parsersLocalScope : this.parsersLocalScope)
+ } catch(e) {
+ console.log(e)
+ }
+ this.scriptLock = false
+
+ scriptVm.setWidget()
+
+
+ }
+
+ setValue(v, options={}) {
+
+ if (this.getProp('event') === 'value') {
+
+ scriptVm.setValueOptions(options)
+
+ this.run({
+ value: v,
+ id: options.id,
+ })
+
+ scriptVm.setValueOptions(options)
+
+ }
+
+ }
+
+ keyboardCallback(e) {
+
+ if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT')) return
+
+ if (this.getProp('keyType') !== 'both' && e.type !== this.getProp('keyType')) return
+
+ if (e.type === 'keydown' && !this.getProp('keyRepeat')) e.preventRepeat()
+
+ e.preventDefault()
+
+ this.run({
+ type: e.type,
+ key: e.key,
+ code: e.code,
+ ctrl: e.ctrlKey,
+ shift: e.shiftKey,
+ alt: e.altKey,
+ meta: e.metaKey
+ })
+
+
+ }
+
+ onRemove() {
+
+
+ if (this.getProp('event') === 'keyboard' && this.getProp('keyBinding')) {
+
+ keyboardJS.withContext('global', ()=>{
+
+ keyboardJS.unbind(this.getProp('keyBinding'), this.keyCb, this.keyCb)
+
+ })
+
+ }
+
+ for (let k in this.timeouts) {
+ clearTimeout(this.timeouts[k])
+ }
+
+ for (let k in this.intervals) {
+ clearInterval(this.intervals[k])
+ }
+
+ super.onRemove()
+
+ }
+
+}
+
+module.exports = Script
diff --git a/src/client/widgets/scripts/variable.js b/src/client/widgets/scripts/variable.js
new file mode 100644
index 00000000..afa114e1
--- /dev/null
+++ b/src/client/widgets/scripts/variable.js
@@ -0,0 +1,41 @@
+var Widget = require('../common/widget'),
+ StaticProperties = require('../mixins/static_properties')
+
+module.exports = class Variable extends StaticProperties(Widget, {bypass: true, interaction: false, visible: false}) {
+
+ static description() {
+
+ return 'Receives / stores a value, to be used in scripts (using the get function) or in properties (using the @{} syntax).'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+
+ }, [
+ 'visible', 'interaction',
+ '_geometry', 'left', 'top', 'width', 'height', 'expand',
+ '_style', 'colorBg', 'colorText', 'colorWidget', 'colorFill', 'colorStroke', 'alphaStroke', 'alphaFillOn', 'alphaFillOff', 'padding', 'css',
+ 'decimals', 'bypass'
+ ], {})
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: null})
+
+ }
+
+
+ setValue(v, options={}) {
+
+ this.value = v
+
+ if (options.sync) this.changed(options)
+
+ }
+
+}
diff --git a/src/client/widgets/sliders/encoder.js b/src/client/widgets/sliders/encoder.js
new file mode 100644
index 00000000..c4efa2bb
--- /dev/null
+++ b/src/client/widgets/sliders/encoder.js
@@ -0,0 +1,268 @@
+var Knob = require('./knob'),
+ Widget = require('../common/widget'),
+ StaticProperties = require('../mixins/static_properties')
+
+
+module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range: {min: 0, max: 1}, sensitivity: 1, steps: ''}) {
+
+ static description() {
+
+ return 'A knob that sends a relative direction infomation instead of an absolute value.'
+
+ }
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _class_specific: 'encoder',
+
+ ticks: {type: 'number', value: 360, help: 'defines the granularity / verbosity of the encoder (number of step for a 360° arc)'},
+ back: {type: '*', value: -1, help: 'Defines which value is sent when rotating the encoder anticlockwise'},
+ forth: {type: '*', value: 1, help: 'Defines which value is sent when rotating the encoder clockwise'},
+ release: {type: 'number', value: '', help: [
+ 'Defines which value is sent when releasing the encoder:',
+ '- Set to `null` to send send no argument in the osc message',
+ '- Can be an `object` if the type needs to be specified'
+ ]},
+ mode: {type: 'string', value: 'circular', choices: ['circular', 'snap', 'vertical'], help: [
+ '- `circular`: relative move in circular motion',
+ '- `snap`: snap to touch position and move in vertical motion',
+ '- `vertical`: relative move in vertical motion',
+ ]},
+ doubleTap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to make the fader reset to its `default` value when receiving a double tap.',
+ 'Can also be an osc address, in which case the widget will just send an osc message (`/ `)'
+ ]},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.previousPercent = 50
+ this.percent = 50
+ this.setValue(this.getProp('release'), {dragged: true})
+
+ }
+
+ angleToPercent(angle, snap) {
+
+ // knob.js without clipping
+ if (snap) return super.angleToPercent(angle)
+
+ var percent = angle - (360 - this.maxAngle) / 2 / this.maxAngle * 100
+ if (percent < 0) percent += 100
+ else if (percent > 100) percent -= 100
+
+ return percent
+
+ }
+
+ percentToAngle(percent, snap) {
+
+ // knob.js without clipping
+ if (snap) return super.percentToAngle(percent)
+
+ return 2 * Math.PI * percent / 100 * (this.maxAngle / 360) // angle relative to maxAngle
+ + Math.PI / 2 // quarter circle offset
+ + Math.PI * (1 - this.maxAngle / 360) // centering offset depending on maxAngle
+
+ }
+
+
+ draginitHandle(e) {
+
+ // knob.js without clipping + extra case for snap
+
+ this.lastOffsetX = e.offsetX
+ this.lastOffsetY = e.offsetY
+
+ if (this.getProp('mode') === 'snap') {
+
+ this.setPercent(this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY), true))
+
+ }
+
+
+
+ }
+
+ dragHandle(e) {
+
+ // knob.js without clipping + extra case for snap
+
+ if ((this.getProp('mode') === 'vertical' && !e.traversing) || e.ctrlKey) {
+ // vertical
+ this.setPercent(-100 * (e.movementY / e.inertia * this.getProp('sensitivity')) / this.height + this.percent)
+
+ } else {
+ // snap or circular
+ var offsetX = this.lastOffsetX + e.movementX,
+ offsetY = this.lastOffsetY + e.movementY
+
+ if (e.traversing || this.getProp('mode') === 'circular') {
+ // circular
+ var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
+ if (Math.abs(diff) < 50 && diff !== 0) this.setPercent(this.percent + diff)
+
+ } else {
+
+ // snap
+ this.setPercent(this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true))
+
+ }
+
+ this.lastOffsetX = offsetX
+ this.lastOffsetY = offsetY
+
+ }
+
+ }
+
+ dragendHandle(e, data, traversing) {
+
+ if (this.getProp('release') === '') return
+
+ this.previousPercent = 50
+ this.percent = 50
+ this.setValue(this.getProp('release'), {sync: true, send: true, dragged: true})
+
+ }
+
+ mousewheelHandle(e) {
+
+ if (e.wheelDeltaX) return
+
+ e.preventDefault()
+ e.stopPropagation()
+
+ var direction = e.wheelDelta / Math.abs(e.wheelDelta),
+ increment = e.ctrlKey?0.25:1
+
+ this.setPercent(this.percent + Math.max(increment, 10 / Math.pow(10, this.decimals + 1)) * direction)
+
+ }
+
+ setPercent(percent) {
+
+ var div = 100 / this.getProp('ticks')
+ percent = Math.round(percent / div) * div
+
+ this.previousPercent = this.percent
+ this.percent = percent
+
+ if (this.percent === this.previousPercent) return
+
+ var dir = this.percent > this.previousPercent
+
+ if (
+ (this.percent >= 0 && this.percent < 25 && this.previousPercent > 75 && this.previousPercent <= 100) ||
+ (this.previousPercent >= 0 && this.previousPercent < 25 && this.percent > 75 && this.percent <= 100)
+
+ ) dir = !dir
+
+ var val = dir ? this.getProp('forth') : this.getProp('back')
+
+ this.setValue(val, {
+ sync: true,
+ send: true,
+ dragged: true,
+ })
+
+ }
+
+ getSpringValue() {
+
+ return this.getProp('release')
+
+ }
+
+ setValue(v,options={}) {
+
+ if (options.fromLocal && v === this.getProp('release')) {
+ this.percent = 50
+ this.previousPercent = 50
+ } else if (
+ !options.dragged ||
+ (v !== this.getProp('forth') && v !== this.getProp('back') && (this.getProp('release') === '' && v !== this.getProp('release')))
+
+ ) return
+
+ this.value = v
+
+ this.batchDraw()
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ draw() {
+
+ var percent = this.percent,
+ d = this.percentToAngle(percent),
+ angle = 2 * Math.PI / 16,
+ min = this.percentToAngle(0),
+ max = this.percentToAngle(100),
+ minRadius = this.minDimension / 6,
+ maxRadius = this.minDimension / 2 - this.cssVars.lineWidth,
+ gaugeWidth = maxRadius - minRadius,
+ gaugeRadius = maxRadius - gaugeWidth / 2
+
+ this.clear()
+
+ if (this.minDimension < 40) {
+ minRadius /= 2
+ gaugeWidth = maxRadius - minRadius
+ gaugeRadius = maxRadius - gaugeWidth / 2
+ }
+
+ // fill
+ this.ctx.globalAlpha = this.cssVars.alphaFill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, d - angle, d + angle)
+ this.ctx.stroke()
+ }
+
+ // stroke
+ if (this.cssVars.lineWidth) {
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ if (this.minDimension > 40) {
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, minRadius, 0, 2 * Math.PI)
+ this.ctx.stroke()
+ }
+
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
+ this.ctx.stroke()
+
+ }
+
+ }
+
+}
diff --git a/src/client/widgets/sliders/fader.js b/src/client/widgets/sliders/fader.js
new file mode 100644
index 00000000..d3689971
--- /dev/null
+++ b/src/client/widgets/sliders/fader.js
@@ -0,0 +1,422 @@
+var {clip} = require('../utils'),
+ Slider = require('./slider')
+
+class Fader extends Slider {
+
+ static description() {
+
+ return 'Vertical / horizontal slider.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'fader',
+
+ design: {type: 'string', value: 'default', choices: ['default', 'round', 'compact'], help: 'Design style'},
+ knobSize: {type: 'number', value: 'auto', help: 'Fader knob size'},
+ horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display the fader horizontally'},
+ pips: {type: 'boolean', value: false, help: 'Set to `true` to show range breakpoints (ignored if `design` is `compact`)'},
+ dashed: {type: 'boolean|array', value: false, help: 'Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]`'},
+ gradient: {type: 'array|object', value: [], help: [
+ 'When set, the meter\'s gauge will be filled with a linear color gradient',
+ '- each item must be a CSS color string.',
+ '- as an `object`: each key must be a number between 0 and 1',
+ '- each item must be a CSS color string.',
+ 'Examples: `[\'blue\', \'red\']`, {\'0\': \'blue\', \'0.9\': \'blue\', \'1\': \'red\'} '
+ ]},
+ snap: {type: 'boolean', value: false, help: 'By default, dragging the widget will modify it\'s value starting from its last value. Setting this to `true` will make it snap directly to the mouse/touch position'},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its `default` value when released'},
+ doubleTap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to make the fader reset to its `default` value when receiving a double tap.',
+ 'Can also be an osc address, in which case the widget will just send an osc message (`/ `)'
+ ]},
+ range: {type: 'object', value: {min:0,max:1}, help: [
+ 'Defines the breakpoints of the fader\'s scale:',
+ '- keys can be percentages and/or `min` / `max`',
+ '- values can be `number` or `object` if a custom label is needed',
+ 'Example: (`{min:{"-inf": 0}, "50%": 0.25, max: {"+inf": 1}}`)'
+ ]},
+ logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale. Set to `-1` for exponential scale.'},
+ sensitivity: {type: 'number', value: 1, help: 'Defines the fader\'s sensitivity when `snap` is `false` '},
+ steps: {type: 'string|number|array', value: '', help: [
+ 'Restricts the widget\'s value:',
+ '- `auto`: use values defined in `range`',
+ '- `number`: define a number of evenly spaced steps',
+ '- `array`: use arbitrary values',
+ ]},
+ origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the fader\'s gauge'},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+
+ }, Fader)
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.container.classList.toggle('horizontal', this.getProp('horizontal'))
+
+ this.gaugeGradient = null
+
+ var dashed = this.getProp('dashed')
+ this.dashed = dashed ? Array.isArray(dashed) ? dashed.map(x=>parseFloat(x)) : [1, 1] : false
+
+ }
+
+ draginitHandle(e) {
+
+ super.draginitHandle(...arguments)
+
+ this.percent = clip(this.percent,[0,100])
+
+ if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) return
+
+ this.percent = this.getProp('horizontal')?
+ (e.offsetX - this.gaugePadding) / (this.width - this.gaugePadding * 2) * 100:
+ (this.height - e.offsetY - this.gaugePadding) / (this.height - this.gaugePadding * 2) * 100
+
+ this.setValue(this.percentToValue(this.percent), {send: true, sync: true, dragged: true})
+
+ }
+
+ dragHandle(e, data) {
+
+ super.dragHandle(...arguments)
+
+ var padding = this.gaugePadding
+ if (this.getProp('design') === 'compact') padding += this.cssVars.knobSize / 2
+
+ this.percent = this.getProp('horizontal')?
+ this.percent + ( e.movementX / (this.width - padding * 2)) * 100 / e.inertia * this.getProp('sensitivity'):
+ this.percent + (-e.movementY / (this.height - padding * 2)) * 100 / e.inertia * this.getProp('sensitivity')
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ percentToCoord(percent) {
+
+ if (this.getProp('horizontal')) {
+ return clip(percent / 100,[0,1]) * (this.width - this.gaugePadding * 2) + this.gaugePadding
+ } else {
+ return (this.height - this.gaugePadding) - clip(percent / 100, [0,1]) * (this.height - this.gaugePadding * 2)
+ }
+
+ }
+
+ resizeHandle(event) {
+
+ var ratio = CANVAS_SCALING * this.scaling
+
+ super.resizeHandle(event)
+
+ if (this.getProp('horizontal')){
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ this.ctx.rotate(-Math.PI/2)
+ this.ctx.translate(-this.height * ratio, 0)
+
+ if (ratio != 1) this.ctx.scale(ratio, ratio)
+ }
+
+ if (this.getProp('gradient')) {
+
+ var colors = this.getProp('gradient')
+
+ if (
+ (Array.isArray(colors) && colors.length > 1) ||
+ (typeof colors === 'object' && Object.keys(colors).length > 1)
+ ) {
+
+ var grad = this.ctx.createLinearGradient(0, this.getProp('horizontal') ? 0 : this.height, 0, this.getProp('horizontal') ? this.width : 0)
+
+ try {
+ if (Array.isArray(colors)) {
+
+ for (var i in colors) {
+ grad.addColorStop(i / (colors.length - 1), colors[i])
+ }
+ this.gaugeGradient = grad
+
+ } else {
+
+ for (var k in colors) {
+ if (!isNaN(k)) {
+ grad.addColorStop(clip(k, [0, 1]), colors[k])
+ }
+ }
+ this.gaugeGradient = grad
+
+ }
+ } catch(err) {
+ this.errors.gradient = err
+ }
+
+ }
+
+ }
+
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ super.cacheCanvasStyle(style)
+
+ if (this.getProp('pips') && this.getProp('design') !== 'compact') this.drawPips()
+
+ }
+
+
+ draw() {
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width
+
+ var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
+ d = Math.round(this.percentToCoord(percent)),
+ o = Math.round(this.percentToCoord(this.valueToPercent(this.originValue))),
+ m = this.getProp('horizontal') ? this.height / 2 : this.width / 2,
+ dashed = this.dashed,
+ compact = this.getProp('design') === 'compact',
+ knobHeight = this.cssVars.knobSize, knobWidth = knobHeight * .6
+
+ this.clear()
+
+ if (this.getProp('pips') && !compact) m -= 10 * PXSCALE
+
+ // sharp border trick
+ if (compact) {
+ if (width % 2 && parseInt(m) === m) m -= 0.5
+ } else {
+ if (width % 2 && parseInt(m) !== m) m -= 0.5
+ }
+
+
+ this.ctx.strokeStyle = this.gaugeGradient || this.cssVars.colorFill
+
+ if (compact) {
+ this.ctx.lineWidth = Math.round(width - this.gaugePadding * 2)
+ } else {
+ this.ctx.lineWidth = this.cssVars.lineWidth
+ }
+
+
+ if (dashed) this.ctx.setLineDash([PXSCALE * dashed[0], PXSCALE * dashed[1]])
+
+
+ if (this.cssVars.alphaFillOff) {
+ // gaugo off
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.moveTo(m, height - this.gaugePadding)
+ this.ctx.lineTo(m, this.gaugePadding)
+ this.ctx.stroke()
+ }
+
+
+ if (this.cssVars.alphaFillOn) {
+ // gaugo on
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.moveTo(m, o)
+ this.ctx.lineTo(m, d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+ if (compact) {
+
+ // stroke
+ if (this.cssVars.lineWidth) {
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(0, 0)
+ this.ctx.lineTo(width, 0)
+ this.ctx.lineTo(width, height)
+ this.ctx.lineTo(0, height)
+ this.ctx.closePath()
+ this.ctx.lineWidth = 2 * this.cssVars.lineWidth
+ this.ctx.stroke()
+
+ }
+
+
+ // flat knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorFill
+
+ this.ctx.beginPath()
+ d = d / (height - this.gaugePadding) * (height-this.gaugePadding - knobHeight)
+ this.ctx.rect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight)
+ this.ctx.fill()
+
+ this.clearRect = [0, 0, width, height]
+
+
+ } else if (this.getProp('design') === 'default') {
+
+
+ if (this.cssVars.alphaStroke) {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorBg
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - knobWidth / 2, d - knobHeight / 2, knobWidth, knobHeight)
+ this.ctx.fill()
+
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+
+ this.ctx.beginPath()
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.rect(m - knobWidth / 2 + 0.5 * PXSCALE, d - knobHeight / 2 + 0.5 * PXSCALE, knobWidth - PXSCALE, knobHeight - PXSCALE)
+ this.ctx.stroke()
+
+ }
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorStroke
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - knobWidth / 6, d, knobWidth / 3, PXSCALE)
+ this.ctx.fill()
+
+ this.clearRect = [m - knobWidth / 2 - PXSCALE, this.gaugePadding - knobHeight / 2 - PXSCALE, knobWidth + 2 * PXSCALE, height - 2 * this.gaugePadding + knobHeight + 2 * PXSCALE]
+
+ } else {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorFill
+
+ this.ctx.beginPath()
+ this.ctx.arc(m, d, knobHeight / 6, 0, 2 * Math.PI)
+ this.ctx.fill()
+
+
+ if (this.cssVars.alphaStroke) {
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.fillStyle = this.cssVars.colorFill
+
+ this.ctx.beginPath()
+ this.ctx.arc(m, d, knobHeight / 2, 0, 2 * Math.PI)
+ this.ctx.fill()
+ }
+
+ this.clearRect = [m - knobHeight / 2 - PXSCALE, this.gaugePadding - knobHeight / 2 - PXSCALE, knobHeight + 2 * PXSCALE, height - 2 * this.gaugePadding + knobHeight + 2 * PXSCALE]
+
+ }
+
+ if (this.getProp('pips') && !compact) {
+ this.ctx.globalAlpha = 1
+ this.ctx.drawImage(this.pips, 0, 0)
+ if (!compact) this.clearRect = [this.clearRect, [m + knobWidth / 2, 0, 12 * PXSCALE + this.pipsTextSize, height]]
+ }
+
+
+ }
+
+ drawPips() {
+
+ this.pips = this.canvas.cloneNode()
+ this.pips.width = this.getProp('horizontal') ? this.height : this.width
+ this.pips.height = !this.getProp('horizontal') ? this.height : this.width
+ this.pipsTextSize = this.fontSize
+
+
+ var ctx = this.pips.getContext('2d',{
+ desynchronized: true,
+ lowLatency: true,
+ alpha: true,
+ preserveDrawingBuffer: true
+ })
+
+ ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily
+ ctx.textBaseline = this.ctx.textBaseline
+ ctx.textAlign = this.ctx.textAlign
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width,
+ m = this.getProp('horizontal') ? this.height / 2 : this.width / 2,
+ compact = this.getProp('design') === 'compact'
+
+ if (width % 2 && parseInt(m) !== m) m -= 0.5
+
+ if (!compact) m -= 16 * PXSCALE - this.cssVars.knobSize * .3 * PXSCALE
+
+
+ ctx.lineWidth = this.fontSize / 11
+ ctx.fillStyle = this.cssVars.colorText
+ ctx.strokeStyle = this.cssVars.colorFill
+
+ var i = 0
+
+ for (var pip of this.rangeKeys) {
+
+ let d = Math.round(this.percentToCoord(pip)),
+ y = compact ? Math.min(d, height - this.gaugePadding - PXSCALE) : d,
+ pipWidth = 4 * PXSCALE
+
+ y += 0.5
+
+
+ ctx.globalAlpha = this.cssVars.alphaPips
+
+ ctx.beginPath()
+
+ ctx.moveTo(m + 7 * PXSCALE, y)
+ ctx.lineTo(m + 7 * PXSCALE + pipWidth, y)
+ ctx.stroke()
+
+
+ var textX = m + 10 * PXSCALE + pipWidth + 4 * PXSCALE,
+ textY = y
+
+ ctx.globalAlpha = this.cssVars.alphaPipsText
+
+
+ if (this.getProp('horizontal')) {
+
+ ctx.save()
+ ctx.translate(textX + 3 * PXSCALE, textY)
+ ctx.rotate(Math.PI/2)
+ ctx.textAlign = 'center'
+ ctx.fillText(this.rangeLabels[i], 0, 0)
+ ctx.restore()
+
+ } else {
+
+ this.pipsTextSize = Math.max(this.pipsTextSize , ctx.measureText(this.rangeLabels[i]).width)
+ ctx.fillText(this.rangeLabels[i], textX, textY)
+
+ }
+
+
+ i++
+
+ }
+
+
+ }
+
+}
+
+
+Fader.cssVariables = Fader.prototype.constructor.cssVariables.concat(
+ {js: 'knobSize', css: '--knob-size', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE}
+)
+
+module.exports = Fader
diff --git a/src/client/widgets/sliders/knob.js b/src/client/widgets/sliders/knob.js
new file mode 100644
index 00000000..b6ebb3c5
--- /dev/null
+++ b/src/client/widgets/sliders/knob.js
@@ -0,0 +1,376 @@
+var {clip} = require('../utils'),
+ Slider = require('./slider')
+
+module.exports = class Knob extends Slider {
+
+ static description() {
+
+ return 'Rotative knob slider.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults({
+
+ _class_specific: 'knob',
+
+ design: {type: 'string', value: 'default', choices: ['default', 'solid', 'line'], help: [
+ 'Design style',
+ 'Note: "solid" design uses "colorStroke" for the central knob color.'
+ ]},
+ mode: {type: 'string', value: 'vertical', choices: ['vertical', 'circular', 'snap'], help: [
+ '- `circular`: relative move in circular motion',
+ '- `snap`: snap to touch position and move in vertical motion',
+ '- `vertical`: relative move in vertical motion',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its `default` value when released'},
+ pips: {type: 'boolean', value: false, help: 'Set to `true` to show the scale\'s breakpoints'},
+ dashed: {type: 'boolean|array', value: false, help: 'Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]`'},
+ angle: {type: 'number', value: 270, help: 'Defines the angle\'s width of the knob, in degrees'},
+ doubleTap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to make the knob reset to its `default` value when receiving a double tap.',
+ 'Can also be an osc address, in which case the widget will just send an osc message (`/ `)'
+ ]},
+ range: {type: 'object', value: {min:0,max:1}, help: [
+ 'Defines the breakpoints of the fader\'s scale:',
+ '- keys can be percentages and/or `min` / `max`',
+ '- values can be `number` or `object` if a custom label is needed',
+ 'Example: (`{min:{"-inf": 0}, "50%": 0.25, max: {"+inf": 1}}`)'
+ ]},
+ logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale. Set to `-1` for exponential scale.'},
+ sensitivity: {type: 'number', value: 1, help: 'Defines the knob\'s sensitivity when `mode` is not `snap` '},
+ steps: {type: 'string|number|array', value: '', help: [
+ 'Restricts the widget\'s value:',
+ '- `auto`: use values defined in `range`',
+ '- `number`: define a number of evenly spaced steps',
+ '- `array`: use arbitrary values',
+ ]},
+ origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the knob\'s gauge'},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+
+ }, Knob)
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.lastOffsetX = 0
+ this.lastOffsetY = 0
+ this.minDimension = 0
+
+ this.maxAngle = this.getProp('angle')
+
+ if (this.getProp('pips')) {
+
+ this.widget.classList.add('has-pips')
+ this.pipTexts = {}
+ for (var k in this.rangeKeys) {
+ this.pipTexts[this.rangeKeys[k]]=this.rangeLabels[k]
+ }
+
+ }
+
+ }
+
+ draginitHandle(e) {
+
+ this.percent = clip(this.percent,[0,100])
+
+ this.lastOffsetX = e.offsetX
+ this.lastOffsetY = e.offsetY
+
+ if (this.getProp('mode') === 'snap') {
+
+ this.percent = this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY))
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+
+ }
+
+ dragHandle(e) {
+
+ if ((this.getProp('mode') === 'vertical' && !e.traversing) || e.ctrlKey) {
+ // vertical
+ this.percent = -100 * (e.movementY / e.inertia * this.getProp('sensitivity')) / this.minDimension + this.percent
+
+ } else {
+ // snap or circular
+ var offsetX = this.lastOffsetX + e.movementX,
+ offsetY = this.lastOffsetY + e.movementY
+
+ if (e.traversing || this.getProp('mode') === 'circular') {
+ // circular
+ var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
+ if (Math.abs(diff) < 50 && diff !== 0) this.percent += diff * 360 / this.maxAngle
+
+ } else {
+
+ // snap
+ this.percent = this.angleToPercent(this.coordsToAngle(offsetX, offsetY))
+
+ }
+
+ this.lastOffsetX = offsetX
+ this.lastOffsetY = offsetY
+
+ }
+
+
+ // this.percent = clip(this.percent,[0,100])
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ coordsToAngle(x,y) {
+
+ var xToCenter = x - this.width /2,
+ yToCenter = y - this.height / 2,
+ angle = Math.atan2(-yToCenter, -xToCenter) * 180 / Math.PI + 90
+
+ return angle<0?360+angle:angle
+
+ }
+
+ angleToPercent(angle, ignoreMaxAngle=false) {
+
+ return ignoreMaxAngle ?
+ clip(angle, [0, 360]) / 360 * 100
+ : clip(angle - (360 - this.maxAngle) / 2, [0, this.maxAngle]) / this.maxAngle * 100
+
+ }
+
+ percentToAngle(percent) {
+
+ percent = clip(percent, [0, 100])
+
+ return 2 * Math.PI * percent / 100 * (this.maxAngle / 360) // angle relative to maxAngle
+ + Math.PI / 2 // quarter circle offset
+ + Math.PI * (1 - this.maxAngle / 360) // centering offset depending on maxAngle
+
+ }
+
+ resizeHandle() {
+
+ super.resizeHandle(...arguments)
+
+ this.minDimension = Math.min(this.width, this.height)
+
+ }
+
+ draw() {
+
+ var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
+ o = this.percentToAngle(this.valueToPercent(this.originValue)),
+ d = this.percentToAngle(percent),
+ min = this.percentToAngle(0),
+ max = this.percentToAngle(100),
+ dashed = this.getProp('dashed'),
+ pips = this.getProp('pips'),
+ minRadius = this.minDimension / 6 - (pips ? this.fontSize * 0.75 : 0) - this.cssVars.lineWidth / 2,
+ maxRadius = this.minDimension / 2 - (pips ? this.fontSize * 2 : 0) - this.cssVars.lineWidth / 2
+
+ if (dashed) dashed = Array.isArray(dashed) ? dashed.map(x=>parseFloat(x)) : [1.5, 1.5]
+
+ var gaugeWidth = maxRadius - minRadius,
+ gaugeRadius = maxRadius - gaugeWidth / 2
+
+ this.clear()
+
+ if (this.getProp('design') === 'default') {
+
+ if (this.minDimension < 40) {
+ minRadius /= 2
+ gaugeWidth = maxRadius - minRadius
+ gaugeRadius = maxRadius - gaugeWidth / 2
+ }
+
+ // fill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash(dashed)
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, o, d, o > d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+
+ // stroke
+ if (this.cssVars.lineWidth) {
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
+ this.ctx.stroke()
+ }
+
+
+ // knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = this.cssVars.lineWidth + .5 * PXSCALE
+
+ let r1 = minRadius + this.gaugePadding,
+ r2 = maxRadius - this.gaugePadding,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+
+ } else if (this.getProp('design') === 'solid') {
+
+ // center
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.fillStyle = this.cssVars.colorStroke
+
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius / 1.25, 0, 2 * Math.PI)
+ this.ctx.fill()
+
+ // fill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash(dashed)
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, o, d, o > d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+ // knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.cssVars.colorBg
+ this.ctx.lineWidth = this.cssVars.lineWidth + .5 * PXSCALE
+
+ let r1 = minRadius,
+ r2 = maxRadius / 1.25 + PXSCALE ,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+
+
+
+ } else {
+
+ // fill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash(dashed)
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, o, d, o > d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+ // knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ let r1 = minRadius * 1.5,
+ r2 = maxRadius + this.cssVars.lineWidth / 2 - 0.5 * PXSCALE,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+
+ }
+
+
+ // pips
+
+ if (pips) {
+
+ this.ctx.lineWidth = this.fontSize / 11 * 1.5
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.globalAlpha = this.cssVars.alphaPips
+
+ for (var pip of this.rangeKeys) {
+
+ let r1 = maxRadius + this.cssVars.lineWidth / 2 + 2 * PXSCALE,
+ r2 = r1 + 4 * PXSCALE,
+ a = 2 * Math.PI - this.percentToAngle(pip)
+
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+
+ }
+ var radius = maxRadius + (this.fontSize + this.cssVars.lineWidth / 2 + 2 * PXSCALE)
+ this.ctx.fillStyle = this.cssVars.colorText
+ this.ctx.globalAlpha = this.cssVars.alphaPipsText
+ for (var p in this.pipTexts) {
+ if (this.pipTexts[p] === undefined || (this.maxAngle === 360 && p === '100')) continue
+ var angle = this.percentToAngle(p),
+ size = this.ctx.measureText(this.pipTexts[p]),
+ x = this.width / 2 + radius * Math.cos(angle) - size.width / 2,
+ y = this.height / 2 + radius * Math.sin(angle)
+ this.ctx.fillText(this.pipTexts[p], x, y)
+ }
+
+ }
+
+ }
+
+}
diff --git a/src/client/widgets/sliders/range.js b/src/client/widgets/sliders/range.js
new file mode 100644
index 00000000..d2b54dc6
--- /dev/null
+++ b/src/client/widgets/sliders/range.js
@@ -0,0 +1,394 @@
+var {clip} = require('../utils'),
+ Fader = require('./fader'),
+ html = require('nanohtml')
+
+var faderDefaults = Fader.defaults()._props()
+
+class Range extends Fader {
+
+ static description() {
+
+ return 'A fader with two heads for setting a range.'
+
+ }
+
+ constructor(options) {
+
+ options.multitouch = true
+
+ super({...options, html: html`
+
+ `})
+
+ this.faders = [
+ new Fader({props:{
+ ...faderDefaults,
+ pips:false,
+ visible: false,
+ horizontal:this.getProp('horizontal'),
+ default:this.getProp('default').length === 2 ? this.getProp('default')[0] : this.getProp('range').min,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ range:this.getProp('range'),
+ decimals:this.getProp('decimals'),
+ logScale:this.getProp('logScale'),
+ sensitivity:this.getProp('sensitivity'),
+ }, parent: this}),
+ new Fader({props:{
+ ...faderDefaults,
+ pips:false,
+ visible: false,
+ horizontal:this.getProp('horizontal'),
+ default:this.getProp('default').length === 2 ? this.getProp('default')[1] : this.getProp('range').max,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ range:this.getProp('range'),
+ decimals:this.getProp('decimals'),
+ logScale:this.getProp('logScale'),
+ sensitivity:this.getProp('sensitivity'),
+ }, parent: this})
+ ]
+
+
+ this.on('change',(e)=>{
+
+ if (e.widget == this) return
+
+ e.stopPropagation = true
+
+ var v = [
+ this.faders[0].getValue(),
+ this.faders[1].getValue()
+ ]
+
+ this.setValue(v, e.options)
+
+ })
+
+ this.touchMap = {}
+
+ this.setValue([
+ this.faders[0].rangeValsMin,
+ this.faders[1].rangeValsMax
+ ])
+
+ }
+
+ resizeHandle(event){
+
+ super.resizeHandle(event)
+
+ for (var f of this.faders) {
+ f.width = this.width
+ f.height = this.height
+ f.gaugePadding = this.gaugePadding
+ }
+
+ }
+
+ draginitHandle(e) {
+
+ var id
+
+ if (!this.touchMap[e.pointerId]) {
+
+ var ndiff, diff = -1
+
+ for (var i in this.faders) {
+
+ if (Object.values(this.touchMap).indexOf(i) != -1) continue
+
+ var coord = this.faders[i].percentToCoord(this.faders[i].valueToPercent(this.faders[i].value)) - (this.getProp('horizontal') ? -1 : 1) * (i == 0 ? -20 : 20)
+
+ ndiff = this.getProp('horizontal')?
+ Math.abs(e.offsetX - coord) :
+ Math.abs(e.offsetY - coord)
+
+ if (diff == -1 || ndiff < diff) {
+ id = i
+ diff = ndiff
+ }
+
+ }
+
+ this.touchMap[e.pointerId] = id
+
+
+ } else if (e.traversing) {
+
+ id = this.touchMap[e.pointerId]
+
+ }
+
+ if (!id) return
+
+ for (var f of this.faders) {
+ f.percent = clip(f.percent,[
+ f.valueToPercent(f.rangeValsMin),
+ f.valueToPercent(f.rangeValsMax)
+ ])
+ }
+
+
+ e.stopPropagation = true
+ this.faders[id].trigger('draginit', e)
+
+ }
+
+ dragHandle(e) {
+
+ var i = this.touchMap[e.pointerId]
+
+ if (!i) return
+
+ if (this.getProp('touchAddress')) {
+ this.sendValue({
+ address: this.getProp('touchAddress'),
+ v: [parseInt(i), 1],
+ })
+ }
+
+ if (e.shiftKey) {
+ this.faders[0].trigger('drag', e)
+ this.faders[1].trigger('drag', e)
+ } else {
+ this.faders[i].trigger('drag', e)
+ }
+
+ }
+
+ dragendHandle(e) {
+
+ var i = this.touchMap[e.pointerId]
+
+ if (!i) return
+
+ e.stopPropagation = true
+ this.faders[i].trigger('dragend', e)
+
+
+ if (this.getProp('touchAddress')) {
+ this.sendValue({
+ address: this.getProp('touchAddress'),
+ v: [parseInt(i), 0],
+ })
+ }
+
+ delete this.touchMap[e.pointerId]
+
+ }
+
+ setValue(v, options={}) {
+
+ if (!v || !v.length || v.length!=2) return
+
+
+ this.faders[0].rangeValsMax = v[1]
+ this.faders[1].rangeValsMin = v[0]
+
+ if (!options.dragged) {
+ this.faders[0].setValue(v[0])
+ this.faders[1].setValue(v[1])
+ }
+ this.value = [
+ this.faders[0].getValue(),
+ this.faders[1].getValue()
+ ]
+
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.batchDraw()
+
+ }
+
+ draw() {
+
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width,
+ fader = this.faders[0]
+
+ var d = Math.round(fader.percentToCoord(fader.valueToPercent(this.faders[this.getProp('horizontal')?0:1].value))),
+ d2 = Math.round(fader.percentToCoord(fader.valueToPercent(this.faders[this.getProp('horizontal')?1:0].value))),
+ m = this.getProp('horizontal') ? this.height / 2 : this.width / 2,
+ dashed = this.getProp('dashed'),
+ compact = this.getProp('design') === 'compact',
+ knobHeight = this.cssVars.knobSize, knobWidth = knobHeight * .6
+
+ this.clear()
+
+ if (this.getProp('pips') && !compact) m -= 10 * PXSCALE
+
+ // sharp border trick
+ if (compact) {
+ if (width % 2 && parseInt(m) === m) m -= 0.5
+ } else {
+ if (width % 2 && parseInt(m) !== m) m -= 0.5
+ }
+
+
+ this.ctx.strokeStyle = this.gaugeGradient || this.cssVars.colorFill
+
+ if (compact) {
+ this.ctx.lineWidth = Math.round(width - this.gaugePadding * 2)
+ } else {
+ this.ctx.lineWidth = this.cssVars.lineWidth
+ }
+
+
+ if (dashed) this.ctx.setLineDash([PXSCALE * dashed[0], PXSCALE * dashed[1]])
+
+
+ if (this.cssVars.alphaFillOff) {
+ // gaugo off
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.moveTo(m, height - this.gaugePadding)
+ this.ctx.lineTo(m, this.gaugePadding)
+ this.ctx.stroke()
+ }
+
+
+ if (this.cssVars.alphaFillOn) {
+ // gaugo on
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.moveTo(m, d)
+ this.ctx.lineTo(m, d2)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+ if (compact) {
+
+ // stroke
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(0, 0)
+ this.ctx.lineTo(width, 0)
+ this.ctx.lineTo(width, height)
+ this.ctx.lineTo(0, height)
+ this.ctx.closePath()
+ this.ctx.lineWidth = 2 * this.cssVars.lineWidth
+ this.ctx.stroke()
+
+
+ // flat knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorFill
+ var compactAdjust = 1 / (height - this.gaugePadding) * (height-this.gaugePadding - knobHeight)
+
+ this.ctx.beginPath()
+ d *= compactAdjust
+ this.ctx.rect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight)
+ this.ctx.fill()
+
+ // extra knob
+ this.ctx.beginPath()
+ d2 *= compactAdjust
+ this.ctx.rect(this.gaugePadding, d2, width - this.gaugePadding * 2, knobHeight)
+ this.ctx.fill()
+
+
+ this.clearRect = [0, 0, width, height]
+
+
+ } else if (this.getProp('design') === 'default') {
+
+ for (let _d of [d, d2]) {
+
+ if (this.cssVars.alphaStroke) {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorBg
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - knobWidth / 2, _d - knobHeight / 2, knobWidth, knobHeight)
+ this.ctx.fill()
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.lineWidth = PXSCALE
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - knobWidth / 2 + 0.5 * PXSCALE, _d - knobHeight / 2 + 0.5 * PXSCALE, knobWidth - PXSCALE, knobHeight - PXSCALE)
+ this.ctx.stroke()
+
+ }
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorWidget
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - knobWidth / 6, _d, knobWidth / 3, PXSCALE)
+ this.ctx.fill()
+
+ }
+
+ this.clearRect = [m - knobWidth / 2 - PXSCALE, this.gaugePadding - knobHeight / 2 - PXSCALE, knobWidth + 2 * PXSCALE, height - 2 * this.gaugePadding + knobHeight + 2 * PXSCALE]
+
+ } else {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.cssVars.colorFill
+
+ this.ctx.beginPath()
+ this.ctx.arc(m, d, 3 * PXSCALE, 0, 2 * Math.PI)
+ this.ctx.fill()
+
+ // extra knob
+ this.ctx.beginPath()
+ this.ctx.arc(m, d2, 3 * PXSCALE, 0, 2 * Math.PI)
+ this.ctx.fill()
+
+
+ if (this.cssVars.alphaStroke) {
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.fillStyle = this.cssVars.colorFill
+
+ this.ctx.beginPath()
+ this.ctx.arc(m, d, 10 * PXSCALE, 0, 2 * Math.PI)
+ this.ctx.fill()
+
+ // extra knob
+ this.ctx.beginPath()
+ this.ctx.arc(m, d2, 10 * PXSCALE, 0, 2 * Math.PI)
+ this.ctx.fill()
+ }
+
+ this.clearRect = [m - 11 * PXSCALE, this.gaugePadding - 11 * PXSCALE, 22 * PXSCALE, height - 2 * this.gaugePadding + 22 * PXSCALE]
+
+ }
+
+ if (this.getProp('pips')) {
+ this.ctx.globalAlpha = 1
+ this.ctx.drawImage(this.pips, 0, 0)
+ if (!compact) this.clearRect = [this.clearRect, [m + knobWidth / 2, 0, 12 * PXSCALE + this.pipsTextSize, height]]
+ }
+
+
+ }
+
+ onRemove() {
+
+ this.faders[0].onRemove()
+ this.faders[1].onRemove()
+ super.onRemove()
+
+ }
+
+}
+
+
+Range.dynamicProps = Range.prototype.constructor.dynamicProps
+ .filter(n => !['spring', 'decimals'].includes(n))
+
+
+module.exports = Range
diff --git a/src/client/widgets/sliders/slider.js b/src/client/widgets/sliders/slider.js
new file mode 100644
index 00000000..792579e3
--- /dev/null
+++ b/src/client/widgets/sliders/slider.js
@@ -0,0 +1,256 @@
+var {clip, mapToScale} = require('../utils'),
+ Canvas = require('../common/canvas'),
+ touchstate = require('../mixins/touch_state'),
+ doubletab = require('../mixins/double_tap'),
+ html = require('nanohtml')
+
+class Slider extends Canvas {
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ `})
+
+ this.container.classList.add('design-' + this.getProp('design'))
+
+ this.value = undefined
+ this.percent = 0
+
+ this.gaugePadding = 0
+
+ this.rangeKeys = []
+ this.rangeVals = []
+ this.rangeLabels = []
+
+ for (var k in this.getProp('range')) {
+ var key = k=='min'?0:k=='max'?100:parseInt(k),
+ val = typeof this.getProp('range')[k] == 'object'?
+ this.getProp('range')[k][Object.keys(this.getProp('range')[k])[0]]:
+ this.getProp('range')[k],
+ label = typeof this.getProp('range')[k] == 'object'?
+ Object.keys(this.getProp('range')[k])[0]:
+ val
+
+ if (Math.abs(label) >= 1000) label = Math.round(label / 1000) + 'k'
+
+ this.rangeKeys.push(key)
+ this.rangeVals.push(val)
+ this.rangeLabels.push(label)
+ }
+ this.rangeValsMax = Math.max(...this.rangeVals),
+ this.rangeValsMin = Math.min(...this.rangeVals)
+
+ this.originValue = this.getProp('origin')=='auto'?
+ this.rangeValsMin:
+ clip(this.getProp('origin'), [this.rangeValsMin,this.rangeValsMax])
+
+ if (this.getProp('doubleTap')) {
+
+ if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
+
+ doubletab(this.widget, ()=>{
+ this.sendValue({v:null, address: this.getProp('doubleTap')})
+ })
+
+ } else {
+
+ doubletab(this.widget, ()=>{
+ this.setValue(this.getSpringValue(),{sync:true, send:true, fromLocal:true})
+ })
+
+ }
+
+ }
+
+
+ this.widget.addEventListener('wheel',this.mousewheelHandleProxy.bind(this))
+
+ touchstate(this, {element: this.widget, multitouch: options.multitouch})
+
+ this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
+ this.on('drag', this.dragHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
+ this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
+
+ this.setSteps()
+
+ this.setValue(this.getSpringValue())
+
+ }
+
+ mousewheelHandleProxy() {
+
+ this.mousewheelHandle(...arguments)
+
+ }
+
+ draginitHandleProxy() {
+
+ this.draginitHandle(...arguments)
+
+ }
+
+ dragHandleProxy() {
+
+ this.dragHandle(...arguments)
+
+ }
+
+ dragendHandleProxy() {
+
+ this.dragendHandle(...arguments)
+
+ }
+
+ mousewheelHandle(e) {
+
+ if (e.deltaX) return
+
+ e.preventDefault()
+ e.stopPropagation()
+
+ var direction = e.deltaY > 0 ? -1 : 1,
+ increment = e.ctrlKey ? 0.25 : 1
+
+ if (this.getProp('steps')) {
+ var i = this.steps.indexOf(this.value)
+ if (i > -1 && i < this.steps.length) {
+ this.setValue(this.steps[i + direction], {sync: true, send: true, fromLocal: true})
+ }
+ } else {
+ this.percent = clip(this.percent + Math.max(increment,10/Math.pow(10,this.decimals + 1)) * direction, [0,100])
+ this.setValue(this.percentToValue(this.percent), {sync: true, send: true, dragged: true})
+ }
+
+ }
+
+ draginitHandle(e, data, traversing) {
+
+ }
+
+ dragHandle(e, data, traversing) {
+
+ }
+
+ dragendHandle(e, data, traversing) {
+
+ if (this.getProp('spring')) {
+ this.setValue(this.getSpringValue(),{sync:true,send:true,fromLocal:true})
+ }
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ super.cacheCanvasStyle(style)
+
+ this.gaugePadding = this.cssVars.padding + this.cssVars.lineWidth
+
+ }
+
+
+
+ getSpringValue() {
+
+ return this.getProp('default') !== '' ? this.getProp('default') : this.originValue
+
+ }
+
+
+ percentToValue(percent) {
+
+ var h = clip(percent,[0,100])
+ for (var i=0;i= this.rangeKeys[i]) {
+ return mapToScale(h, [this.rangeKeys[i], this.rangeKeys[i + 1]], [this.rangeVals[i], this.rangeVals[i + 1]], -1, this.getProp('logScale'))
+ }
+ }
+
+ }
+
+ valueToPercent(value) {
+
+ for (var i=0;i this.rangeVals[i] && value <= this.rangeVals[i+1] && value >= this.rangeVals[i]) ||
+ (this.rangeVals[i+1] < this.rangeVals[i] && value >= this.rangeVals[i+1] && value <= this.rangeVals[i])
+ ) {
+ return mapToScale(value, [this.rangeVals[i], this.rangeVals[i + 1]], [this.rangeKeys[i], this.rangeKeys[i + 1]], -1, this.getProp('logScale'), true)
+ }
+ }
+
+ }
+
+ setValue(v,options={}) {
+
+ if (typeof v != 'number') return
+ if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
+
+ var value = clip(v,[this.rangeValsMin,this.rangeValsMax])
+
+ if ((options.dragged || options.fromLocal) && this.value.toFixed(this.decimals) == value.toFixed(this.decimals)) options.send = false
+
+ this.value = value
+
+ if (this.getProp('steps')) {
+
+ var diff = this.steps.map(x => Math.abs(x - this.value)),
+ index = diff.indexOf(Math.min(...diff)),
+ val = this.steps[index]
+
+ if (!isNaN(val)) this.value = clip(val, [this.rangeValsMin,this.rangeValsMax])
+
+ }
+
+ if (!options.dragged || options.fromScript) this.percent = this.valueToPercent(this.value)
+
+ this.batchDraw()
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ setSteps() {
+
+ if (this.getProp('steps')) {
+ var steps = this.getProp('steps')
+ this.steps = Array.isArray(steps) ?
+ steps : typeof steps === 'number' ?
+ Array(steps).fill(0).map((x, i) => i / (steps - 1) * (this.rangeValsMax - this.rangeValsMin) + this.rangeValsMin)
+ : this.rangeVals
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'steps':
+ this.setSteps()
+ return
+
+ }
+
+ }
+
+ onRemove() {
+
+ super.onRemove()
+
+ }
+
+}
+
+Slider.dynamicProps = Slider.prototype.constructor.dynamicProps
+ .concat([
+ 'steps',
+ 'spring',
+ 'sensitivity',
+ 'default',
+ ])
+
+module.exports = Slider
diff --git a/src/client/widgets/utils.js b/src/client/widgets/utils.js
new file mode 100644
index 00000000..d0e5f916
--- /dev/null
+++ b/src/client/widgets/utils.js
@@ -0,0 +1,118 @@
+module.exports = {
+
+ clip: function(value,range) {
+
+ value = parseFloat(value)
+
+ if (isNaN(value)) value = range[0]
+
+ return Math.max(Math.min(range[0], range[1]), Math.min(value, Math.max(range[0], range[1])))
+
+ },
+
+ // map a value from a scale to another
+ // value: number
+ // rangeIn: [number, number]
+ // rangeOut: [number, number]
+ // decimals: number (-1 to bypass)
+ // log: true, or manual log scale (max log value)
+ // revertLog: boolean
+ mapToScale: function(value, rangeIn, rangeOut, decimals, log, revertlog) {
+
+ // clip in
+ value = module.exports.clip(value,[rangeIn[0], rangeIn[1]])
+
+
+ // normalize
+ value = (value - rangeIn[0]) / (rangeIn[1] - rangeIn[0])
+
+ // log scale
+ if (log) {
+
+ var logScale = revertlog ? Math.abs(rangeIn[1] - rangeIn[0]) :
+ Math.abs(rangeOut[1] - rangeOut[0])
+
+ if (log !== true && log !== -1) logScale = Math.abs(log)
+ else if (logScale >= 100) logScale /= 10
+ else logScale = Math.max(logScale, 10)
+
+ if (log < 0) revertlog = !revertlog
+
+ value = revertlog ?
+ Math.log(value * (logScale - 1) + 1) / Math.log(logScale) :
+ Math.pow(logScale, value) / (logScale - 1) - 1 / (logScale - 1)
+
+ }
+
+ // scale out
+ value = value * (rangeOut[1] - rangeOut[0]) + rangeOut[0]
+
+ // clip out
+ value = module.exports.clip(value, [rangeOut[0], rangeOut[1]])
+
+ // decimals
+ if (decimals !== -1) value = parseFloat(value.toFixed(decimals))
+
+ return value
+
+ },
+
+ hsbToRgb: function(hsb) {
+ var rgb = {}
+ var h = hsb.h
+ var s = hsb.s*255/100
+ var v = hsb.b*255/100
+ if(s == 0) {
+ rgb.r = rgb.g = rgb.b = v
+ } else {
+ var t1 = v
+ var t2 = (255-s)*v/255
+ var t3 = (t1-t2)*(h%60)/60
+ if(h==360) h = 0
+ if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
+ else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
+ else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
+ else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
+ else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
+ else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
+ else {rgb.r=0; rgb.g=0; rgb.b=0}
+ }
+ return rgb
+ },
+
+ rgbToHsb: function(rgb) {
+ var hsb = {h: 0, s: 0, b: 0}
+ var min = Math.min(rgb.r, rgb.g, rgb.b)
+ var max = Math.max(rgb.r, rgb.g, rgb.b)
+ var delta = max - min
+ hsb.b = max
+ hsb.s = max != 0 ? 255 * delta / max : 0
+ if (hsb.s != 0) {
+ if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta
+ else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta
+ else hsb.h = 4 + (rgb.r - rgb.g) / delta
+ } else hsb.h = 0
+ hsb.h *= 60
+ if (hsb.h < 0) hsb.h += 360
+ hsb.s *= 100/255
+ hsb.b *= 100/255
+ return hsb
+ },
+
+ urlParser: (()=>{
+
+ var parser = document.createElement('a'),
+ localUrlRe = /(^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.1[6-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.2[0-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.3[0-1]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^192\.168\.[0-9]{1,3}\.[0-9]{1,3}$)/
+
+ parser.isLocal = ()=>{
+ return parser.hostname.match(localUrlRe)
+ }
+
+ return (url)=>{
+ parser.href = url
+ return parser
+ }
+
+ })()
+
+}
diff --git a/src/client/widgets/vm.js b/src/client/widgets/vm.js
new file mode 100644
index 00000000..08416986
--- /dev/null
+++ b/src/client/widgets/vm.js
@@ -0,0 +1,134 @@
+var loopProtect = require('loop-protect'),
+ {deepCopy} = require('../utils'),
+ globals
+
+class Vm {
+
+ constructor() {
+
+ if (!globals) {
+ globals = {
+ screen: {width: screen.width, height: screen.height},
+ env: deepCopy(ENV),
+ ip: IP,
+ url: document.location.host,
+ platform: navigator.platform
+ }
+ }
+
+ this.sandbox = document.createElement('iframe')
+ this.sandbox.style.display = 'none'
+ this.sandbox.sandbox = 'allow-same-origin'
+
+ // attach sandbox
+ document.documentElement.appendChild(this.sandbox)
+
+ // sandboxed function prototype
+ this.safeFunctionProto = this.sandbox.contentWindow.Function
+
+ // block requests
+ this.sandbox.contentWindow.document.open()
+ this.sandbox.contentWindow.document.write(' ')
+ this.sandbox.contentWindow.document.close()
+
+ // init infinite loop guard
+ loopProtect.alias = '__protect'
+ loopProtect.hit = function(line){
+ throw 'Potential infinite loop found on line ' + line
+ }
+ this.sandbox.contentWindow.__protect = loopProtect
+
+ // global context
+ this.registerGlobals()
+
+ // detach sandbox
+ document.documentElement.removeChild(this.sandbox)
+
+ }
+
+ registerGlobals() {
+
+ this.sandbox.contentWindow.console = console
+ this.sandbox.contentWindow.setTimeout =
+ this.sandbox.contentWindow.setInterval = ()=>{
+ throw 'setTimeout and setInterval can\'t be used in the JS sandbox'
+ }
+ this.sandbox.contentWindow.globals = globals
+
+ // sanitize globals
+ for (var imports of ['__protect', 'console', 'setTimeout', 'setInterval', 'globals']) {
+ this.sanitize(this.sandbox.contentWindow[imports])
+ }
+
+ }
+
+ sanitize(object) {
+
+ // non-primitives created outside the sandbox context can leak
+ // the host window object... let's nuke that !
+ // (we only nuke functions and objects/arrays because we don't pass anything else)
+ var t = typeof o
+ if (t === 'function' || (t === 'object' && o !== null)) {
+ if (o.__proto__) {
+ if (t === 'function') {
+ o.__proto__.constructor = this.safeFunctionProto
+ } else {
+ o.__proto__.constructor.constructor = this.safeFunctionProto
+ }
+ }
+ for (var k in o) {
+ this.sanitize(o[k])
+ }
+ }
+
+ }
+
+ compile(code, defaultContext) {
+
+ // var contextInit = 'var locals = locals;',
+ var contextInit = '',
+ contextKeys = ['__VARS'],
+ contextValues = [{}]
+
+ if (defaultContext) {
+ for (var k in defaultContext) {
+ contextInit += `var ${k} = ${k} === undefined ? ${JSON.stringify(defaultContext[k])} : ${k};`
+ contextKeys.push(k)
+ contextValues.push(defaultContext[k])
+ }
+ }
+
+ var compiledCode = new this.safeFunctionProto(
+ ...contextKeys, 'locals',
+ loopProtect('"use strict";' + contextInit + code)
+ .replace(/;\n(if \(__protect.*break;)\n/g, ';$1') // prevent loop protect from breaking stack linenumber
+ .replace(/(VAR_[0-9]+)/g, '__VARS.$1')
+ )
+
+
+ return (context, locals)=>{
+
+ var __contextValues = deepCopy(contextValues)
+ var __VARS = __contextValues[0]
+ for (var k in context) {
+ var index = contextKeys.indexOf(k)
+ if (index !== -1) {
+ __contextValues[index] = context[k]
+ } else {
+ __VARS[k] = context[k]
+ }
+ }
+
+ __contextValues.push(locals)
+
+ this.sanitize(__contextValues)
+
+ return compiledCode.apply(null, __contextValues)
+
+ }
+
+ }
+
+}
+
+module.exports = Vm
diff --git a/src/html/client.html b/src/html/client.html
new file mode 100644
index 00000000..5d1f18f0
--- /dev/null
+++ b/src/html/client.html
@@ -0,0 +1,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/html/launcher.html b/src/html/launcher.html
new file mode 100644
index 00000000..60f6e86b
--- /dev/null
+++ b/src/html/launcher.html
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/launcher/context-menu.js b/src/launcher/context-menu.js
new file mode 100644
index 00000000..ba6a7260
--- /dev/null
+++ b/src/launcher/context-menu.js
@@ -0,0 +1,28 @@
+var {remote} = eval('require(\'electron\')'),
+ {Menu, MenuItem} = remote.require('electron'),
+ menu = new Menu()
+
+
+menu.append(new MenuItem({role: 'undo'}))
+menu.append(new MenuItem({role: 'redo'}))
+menu.append(new MenuItem({type: 'separator'}))
+menu.append(new MenuItem({role: 'copy'}))
+menu.append(new MenuItem({role: 'paste'}))
+
+// not working currently
+// menu.append(new MenuItem({type: 'submenu' , label: 'App', submenu: [
+// new MenuItem({
+// label: 'Relaunch',
+// click: ()=>{
+// app.relaunch()
+// app.exit(0)
+// }
+// }),
+// ]}))
+
+
+window.addEventListener('contextmenu', function(e) {
+ menu.items[3].enabled = !!window.getSelection().toString()
+ menu.items[4].enabled = e.target.tagName === 'INPUT' && !e.target.getAttribute('disabled')
+ menu.popup({ window: remote.getCurrentWindow(), x: e.pageX, y: e.pageY - (document.body.scrollTop || document.documentElement.scrollTop) })
+}, false)
diff --git a/src/launcher/index.js b/src/launcher/index.js
new file mode 100644
index 00000000..8e61e3fb
--- /dev/null
+++ b/src/launcher/index.js
@@ -0,0 +1,15 @@
+require('../client/globals')
+
+document.addEventListener('DOMContentLoaded', function(event) {
+
+ DOM.init()
+ require('../client/events/event-emitter')
+ require('../client/ui/ui-workspace')
+ require('../client/ui/zoom')
+
+ setTimeout(()=>{
+ require('./main')
+ }, 10)
+
+
+})
diff --git a/src/launcher/main.js b/src/launcher/main.js
new file mode 100644
index 00000000..ab6352e4
--- /dev/null
+++ b/src/launcher/main.js
@@ -0,0 +1,28 @@
+var terminal = require('./terminal'),
+ settings = require('./settings'),
+ html = require('nanohtml')
+
+require('./toolbar')
+require('./context-menu')
+
+DOM.get(document, '#osc-greeting-header')[0].appendChild(html`${window.PACKAGE.productName} v${window.PACKAGE.version} `)
+
+if (settings.remote.read('checkForUpdates') && navigator.onLine) {
+
+ var request = new XMLHttpRequest()
+ request.open('GET', 'https://api.github.com/repos/jean-emmanuel/open-stage-control/tags', true)
+
+ request.onload = function() {
+ if (request.status >= 200 && request.status < 400) {
+ var data = JSON.parse(request.responseText)
+
+ if (data[0].name != 'v' + window.PACKAGE.version) {
+ terminal.log(`(INFO) A new version is available : ${data[0].name} `, 'info')
+ }
+
+ }
+ }
+
+ request.send()
+
+}
diff --git a/src/launcher/settings.js b/src/launcher/settings.js
new file mode 100644
index 00000000..61a386b7
--- /dev/null
+++ b/src/launcher/settings.js
@@ -0,0 +1,246 @@
+var {remote, ipcRenderer} = eval('require(\'electron\')'),
+ {dialog} = remote.require('electron'),
+ fs = remote.require('fs'),
+ settings = remote.getGlobal('settings'),
+ {icon} = require('../client/ui/utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ terminal = require('./terminal'),
+ options_remote = settings.read('options')
+
+class Settings {
+
+ constructor() {
+
+ this.remote = settings
+ this.container = DOM.get('#osc-container')[0].appendChild(html` `)
+ this.names = []
+ this.options = {}
+ this.configPath = null
+ for (var i in options_remote) {
+ this.options[i] = options_remote[i]
+ }
+
+ this.create()
+ this.write(true)
+
+ ipcRenderer.on('server-started', ()=>{
+ this.disable()
+ })
+ ipcRenderer.on('server-stopped', ()=>{
+ this.enable()
+ })
+
+ }
+
+ save() {
+
+ if (!this.configPath) return this.saveAs()
+ fs.writeFile(this.configPath, JSON.stringify(this.options), (err, fdata)=>{
+
+ if (err) console.error(err)
+ else terminal.log('(INFO) Config saved in ' + this.configPath)
+
+ })
+
+ }
+
+ saveAs() {
+
+ dialog.showSaveDialog({
+ title: 'Open File',
+ filters:[{name: 'OSC Config (.config)', extensions: ['config']}],
+ properties: ['openFile']
+ }).then((file)=>{
+ if (file.canceled || !file.filePath) return
+ this.configPath = file.filePath
+ if (this.configPath.split('.').pop() !== 'config') this.configPath += '.config'
+ this.save()
+ })
+
+ }
+
+ load() {
+
+ dialog.showOpenDialog({
+ title: 'Open File',
+ filters:[{name: 'OSC Config (.config)', extensions: ['config']}],
+ properties: ['openFile']
+ }).then((file)=>{
+ if (file.canceled || !file.filePaths.length) return
+ this.options = JSON.parse(fs.readFileSync(file.filePaths[0], 'utf-8'))
+ this.create()
+ this.write()
+ terminal.log('(INFO) Config loaded from ' + file.filePaths[0])
+ this.configPath = file.filePaths[0]
+ })
+
+ }
+
+
+ write(tmp) {
+
+ for (var i in this.options) {
+ if (this.options[i] === '' || !this.names.includes(i)) {
+ delete this.options[i]
+ }
+ }
+
+ settings.write('options', this.options, tmp)
+
+ }
+
+
+ create() {
+
+ this.container.innerHTML = ''
+
+ for (let k in settings.options) {
+
+ if (settings.options[k].launcher === false) continue
+
+ let data = settings.options[k],
+ name = data.alias || k,
+ field = html` `,
+ label = field.appendChild(html`${name} `),
+ input = field.appendChild(html` `),
+ toggle, browse, reset
+
+ this.names.push(name)
+
+ let value = this.options[name] === undefined ? '' : this.options[name],
+ strValue = Array.isArray(value) ? value.map(x=>x.includes(' ') ? '"'+x+'"' : x).join(' ') : value
+
+
+ label.addEventListener('click', (e)=>{
+ terminal.log(`(HELP) --${name}: ${data.describe}`, 'help')
+ })
+
+ if (data.type === 'boolean') {
+
+ toggle = field.appendChild(html`
+ ${raw(icon('check'))}
+ `)
+ toggle.addEventListener('click', (e)=>{
+ input.value = toggle.classList.toggle('on')
+ DOM.dispatchEvent(input, 'change')
+ })
+
+ }
+
+ if (data.file) {
+
+ browse = field.appendChild(html`
+ ${raw(icon('folder-open'))}
+ `)
+
+ browse.addEventListener('click', (e)=>{
+ e.preventDefault()
+ dialog.showOpenDialog({
+ title: 'Open ' + (data.file.folder ? 'folder' : 'file'),
+ filters:[{name: data.file.name, extensions: data.file.extensions}],
+ properties: data.file.folder ? ['openDirectory'] : ['openFile']
+ }).then((file)=>{
+ input.value = file.filePaths
+ DOM.dispatchEvent(input, 'change')
+ })
+ })
+
+ }
+
+ reset = field.appendChild(html`
+ ${raw(icon('times'))}
+ `)
+ reset.addEventListener('click', ()=>{
+ input.value = ''
+ DOM.dispatchEvent(input, 'change')
+ })
+
+ input.value = strValue
+
+ this.container.appendChild(field)
+
+ input.addEventListener('change', (e)=>{
+ let v = input.value.trim(),
+ fail = false
+
+ try {
+ if (data.type == 'boolean') {
+ v = v && v !== 'false' ? true : ''
+ input.value = v
+ toggle.classList.toggle('on', v)
+ } else if (v && data.type === 'array'){
+ v = v.replace(/("[^"]*"|'[^']*')/g, (m)=>{
+ return m.substr(1, m.length - 2).replace(/\s/, '_SPaCE_')
+ })
+ v = v.split(' ')
+ v = v.map(x=>x.replace(/_SPaCE_/g, ' '))
+ } else if (v && data.type == 'number'){
+ v = parseFloat(v)
+ }
+ } catch (err) {
+ fail = err
+ }
+
+ if (fail || v !== '' && data.check && data.check(v, this.options) !== true) {
+ let error = `(ERROR) --${name}: ${fail || data.check(v, this.options)}`
+ field.classList.add('error')
+ if (field.getAttribute('data-error') !== error) {
+ terminal.log(error, 'error')
+ field.setAttribute('data-error', error)
+ }
+ } else {
+ field.classList.remove('error')
+ field.removeAttribute('data-error')
+ this.options[name] = v
+ }
+
+ if (data.restart && !field.classList.contains('restart') && v != value) {
+ field.classList.add('restart')
+ field.classList.add('warning')
+ terminal.log(`(WARNING) --${name}: The launcher must be restarted for this change to take effect.`, 'warning')
+ } else if (data.restart && field.classList.contains('restart') && v == value) {
+ field.classList.remove('restart')
+ field.classList.remove('warning')
+ }
+
+
+ if (!e.detail || !e.detail.stop) {
+ DOM.each(this.container, 'input', (el)=>{
+ if (el === input) return
+ DOM.dispatchEvent(el, 'change', {stop: true})
+ })
+ this.write()
+ }
+
+ })
+
+ }
+
+ DOM.each(this.container, 'input', (el)=>{
+ DOM.dispatchEvent(el, 'change', {stop: true})
+ })
+
+ }
+
+ disable() {
+
+ this.container.classList.add('disabled')
+ DOM.each(this.container, 'input', (el)=>{
+ el.setAttribute('disabled', true)
+ })
+
+ }
+
+ enable() {
+
+ this.container.classList.remove('disabled')
+ DOM.each(this.container, 'input', (el)=>{
+ el.removeAttribute('disabled')
+ })
+
+ }
+
+}
+
+module.exports = new Settings()
diff --git a/src/launcher/terminal.js b/src/launcher/terminal.js
new file mode 100644
index 00000000..e4035493
--- /dev/null
+++ b/src/launcher/terminal.js
@@ -0,0 +1,67 @@
+var {ipcRenderer} = eval('require(\'electron\')'),
+ ansiHTML = require('ansi-html'),
+ html = require('nanohtml')
+
+class Terminal {
+
+ constructor(options) {
+
+ this.content = DOM.get(options.selector)[0]
+ this.autoSroll = true
+ this.length = 0
+ this.maxLength = 500
+
+ ipcRenderer.on('stdout', (e, msg)=>{
+ this.log(ansiHTML(msg), 'log')
+ })
+
+ ipcRenderer.on('stderr', (e, msg)=>{
+ if (msg.includes('\n at') && msg.split('\n at').length > 2) {
+ msg = msg.replace('\n at', ''
+ }
+ this.log(ansiHTML(msg), 'error')
+ })
+
+ this.content.addEventListener('click', (e)=>{
+ if (e.target.classList.contains('trace-button')) {
+ e.target.parentNode.classList.toggle('show')
+ }
+ })
+
+ }
+
+ log(message, iclass = '') {
+
+ var node = html`
`
+ node.innerHTML = message
+
+ this.content.appendChild(node)
+
+ if (++this.length > this.maxLength) this.purge()
+
+ if (this.autoSroll) {
+ node.scrollIntoView()
+ }
+
+ }
+
+ purge() {
+
+ var children = [...this.content.children]
+ for (var i = 0; i < this.maxLength / 2; i++) {
+ this.content.removeChild(children[i])
+ }
+ this.length = this.maxLength / 2 + 1
+
+ }
+
+ clear() {
+
+ this.content.innerHTML = ''
+ this.length = 0
+
+ }
+
+}
+
+module.exports = new Terminal({selector: '#osc-terminal'})
diff --git a/src/launcher/toolbar.js b/src/launcher/toolbar.js
new file mode 100644
index 00000000..a319d5ae
--- /dev/null
+++ b/src/launcher/toolbar.js
@@ -0,0 +1,147 @@
+var {remote, ipcRenderer} = eval('require(\'electron\')'),
+ {Menu, MenuItem} = remote.require('electron'),
+ menu = new Menu(),
+ terminal = require('./terminal'),
+ settings = require('./settings'),
+ midilist = remote.getGlobal('midilist'),
+ openDocs = remote.getGlobal('openDocs'),
+ serverStarted = false,
+ serverStart = ()=>{
+ if (serverStarted) return
+ ipcRenderer.send('start')
+ },
+ serverStop = ()=>{
+ if (!serverStarted) return
+ ipcRenderer.send('stop')
+ }
+
+var start = new MenuItem({
+ label: 'Start',
+ click: serverStart
+})
+var stop = new MenuItem({
+ label: 'Stop',
+ click: serverStop
+})
+var newWindow = new MenuItem({
+ label: 'New window',
+ visible: false,
+ click: ()=>{
+ ipcRenderer.send('openClient')
+ }
+})
+menu.append(start)
+menu.append(stop)
+menu.append(newWindow)
+menu.append(new MenuItem({
+ type: 'separator'
+}))
+menu.append(new MenuItem({
+ label: 'Load',
+ click: ()=>{
+ settings.load()
+ }
+}))
+menu.append(new MenuItem({
+ label: 'Save',
+ click: ()=>{
+ settings.save()
+ }
+}))
+menu.append(new MenuItem({
+ label: 'Save as...',
+ click: ()=>{
+ settings.saveAs()
+ }
+}))
+menu.append(new MenuItem({
+ type: 'separator'
+}))
+menu.append(new MenuItem({
+ label: 'List MIDI Devices',
+ click: ()=>{
+ midilist()
+ }
+}))
+menu.append(new MenuItem({type: 'submenu' , label: 'Console', submenu: [
+ new MenuItem({
+ label: 'Clear',
+ click: ()=>{
+ terminal.clear()
+ }
+ }),
+ new MenuItem({
+ label: 'Autoscroll',
+ type: 'checkbox',
+ checked: true,
+ click: function(e){
+ terminal.autoSroll = e.checked
+ }
+ }),
+ new MenuItem({
+ label: 'Check for updates at startup',
+ type: 'checkbox',
+ checked: settings.remote.read('checkForUpdates'),
+ click: (e)=>{
+ settings.remote.write('checkForUpdates', e.checked)
+ }
+ })
+]}))
+menu.append(new MenuItem({
+ type: 'separator'
+}))
+// menu.append(new MenuItem({
+// label: 'Restart',
+// click: ()=>{
+// app.relaunch()
+// app.exit(0)
+// }
+// }))
+menu.append(new MenuItem({
+ label: 'Documentation',
+ click: ()=>{
+ openDocs()
+ }
+}))
+menu.append(new MenuItem({
+ role: 'Quit'
+}))
+
+class Toolbar {
+
+ constructor() {
+
+ this.container = DOM.get('osc-toolbar#menu')[0]
+ this.startButton = DOM.get('osc-toolbar#start')[0]
+
+ this.container.addEventListener('click', (e)=>{
+ this.container.classList.add('on')
+ start.visible = !serverStarted
+ stop.visible = !!serverStarted
+ newWindow.visible = !!serverStarted
+ menu.popup({window: remote.getCurrentWindow(), x: parseInt(PXSCALE), y: parseInt(40 * PXSCALE)})
+ })
+
+ menu.on('menu-will-close', ()=>{
+ this.container.classList.remove('on')
+ })
+
+ this.startButton.addEventListener('click', (e)=>{
+ if (!serverStarted) serverStart()
+ else serverStop()
+ })
+
+ ipcRenderer.on('server-started', ()=>{
+ serverStarted = true
+ this.startButton.classList.add('started')
+ })
+ ipcRenderer.on('server-stopped', ()=>{
+ serverStarted = false
+ this.startButton.classList.remove('started')
+ })
+
+ }
+
+}
+
+module.exports = new Toolbar()
diff --git a/src/python/head.py b/src/python/head.py
new file mode 100644
index 00000000..cb59c2ec
--- /dev/null
+++ b/src/python/head.py
@@ -0,0 +1,33 @@
+from sys import argv, stdin, stdout, version_info, version, exit
+from binascii import hexlify, unhexlify
+import traceback
+import json as JSON
+import re
+
+def ipc_send(name, data):
+ print(JSON.dumps([name, data]))
+ stdout.flush()
+
+try:
+ import rtmidi
+ from rtmidi.midiconstants import *
+
+ API = rtmidi.API_UNIX_JACK if 'jack' in argv else rtmidi.API_UNSPECIFIED
+ if API == rtmidi.API_UNIX_JACK and rtmidi.API_UNIX_JACK not in rtmidi.get_compiled_api():
+ API = rtmidi.API_UNSPECIFIED
+ ipc_send('log', '(ERROR, MIDI) python-rtmidi was not compiled with jack midi support, falling back to default API')
+
+ JACK = API == rtmidi.API_UNIX_JACK
+
+ in_dev = rtmidi.MidiIn(API, 'MIDI->OSC probe')
+ out_dev = rtmidi.MidiOut(API, 'OSC->MIDI probe')
+
+except:
+ ipc_send('log', '(ERROR, MIDI) python-rtmidi not found (or wrong version) (running with python %s)' % ".".join(map(str, version_info[:3])))
+ ipc_send('log', '(INFO, MIDI) Get python-rtmidi at https://spotlightkid.github.io/python-rtmidi/')
+ exit()
+
+if version_info.major == 3:
+ raw_input = input
+
+debug = 'debug' in argv
diff --git a/src/python/list.py b/src/python/list.py
new file mode 100644
index 00000000..627d44bf
--- /dev/null
+++ b/src/python/list.py
@@ -0,0 +1,24 @@
+from head import *
+
+def list():
+
+ message = []
+
+ message.append('(INFO, MIDI) Inputs')
+ message.append(' -1: Void (bypass)')
+
+ for i in range(in_dev.get_port_count()):
+ message.append(' %i: %s' % (i, in_dev.get_port_name(i)))
+
+ message.append('(INFO, MIDI) Outputs')
+ message.append(' -1: Void (bypass)')
+
+ for i in range(out_dev.get_port_count()):
+ message.append(' %i: %s' % (i, out_dev.get_port_name(i)))
+
+ ipc_send('log', '\n'.join(message))
+
+
+if __name__ == '__main__':
+
+ list()
diff --git a/src/python/midi.py b/src/python/midi.py
new file mode 100644
index 00000000..1f6501c3
--- /dev/null
+++ b/src/python/midi.py
@@ -0,0 +1,248 @@
+from head import *
+from list import *
+from utils import *
+
+ipc_send('version', '1.2.0')
+
+if 'list' in argv:
+ list()
+
+if 'list-only' in argv:
+ list()
+ exit()
+
+# option: act as if displayed program is between 1-128 instead of 0-127
+PROGRAM_CHANGE_OFFSET = 'pc_offset' in argv
+
+inputs = {}
+outputs = {}
+
+for arg in argv:
+
+ if 'python/midi.py' in arg:
+
+ pass # in case we're using pre-compiled binaries
+
+ elif type(arg) == str and ':' in arg:
+
+ name, *ports = arg.split(':')
+ ports = ':'.join(ports) # port names may contain colons
+
+ inputs[name] = rtmidi.MidiIn(API, name if not JACK else name + '_in')
+ outputs[name] = rtmidi.MidiOut(API, name if not JACK else name + '_out')
+
+ if debug:
+ ipc_send('log','(DEBUG, MIDI) device "%s" created' % name)
+
+
+ if ports == 'virtual':
+
+ try:
+ inputs[name].open_virtual_port('midi_in')
+ outputs[name].open_virtual_port('midi_out')
+ if debug:
+ ipc_send('log','(DEBUG, MIDI) virtual ports opened for device "%s"' % name)
+ except:
+ ipc_send('error', 'can\'t open virtual port "%s"' % name)
+
+ elif ',' in ports:
+
+ in_port, out_port = ports.split(',')
+
+ if in_port.isdigit() or in_port == '-1':
+ in_port = int(in_port)
+ else:
+ for i in range(in_dev.get_port_count()):
+ if in_port.lower() in in_dev.get_port_name(i).lower():
+ in_port = i
+ break
+
+ if out_port.isdigit() or out_port == '-1':
+ out_port = int(out_port)
+ else:
+ for i in range(out_dev.get_port_count()):
+ if out_port.lower() in out_dev.get_port_name(i).lower():
+ out_port = i
+ break
+
+ if type(in_port) != int or in_port >= in_dev.get_port_count():
+ ipc_send('error', 'can\'t connect to input port "%s"' % in_port)
+ break
+
+ if type(out_port) != int or out_port >= out_dev.get_port_count():
+ ipc_send('error', 'can\'t connect to output port "%s"' % out_port)
+ break
+
+ if in_port != -1:
+
+ try:
+ inputs[name].open_port(in_port, 'midi_in')
+ if debug:
+ ipc_send('log','(DEBUG, MIDI) device "%s" connected to input port %s (%s)' % (name, in_port, in_dev.get_port_name(in_port)))
+ except:
+ ipc_send('error', 'can\'t connect input to port %i: %s' % (in_port, in_dev.get_port_name(in_port)))
+
+ if out_port != -1:
+
+ try:
+ outputs[name].open_port(out_port, 'midi_out')
+ if debug:
+ ipc_send('log','(DEBUG, MIDI) device "%s" connected to output port %s (%s)' % (name, out_port, out_dev.get_port_name(out_port)))
+ except:
+ ipc_send('error', 'can\'t connect to output port %i: %s' % (out_port, out_dev.get_port_name(out_port)))
+
+
+def create_callback(name):
+
+ def receive_midi(event, data):
+
+ osc = {}
+ osc['args'] = []
+ osc['host'] = 'midi'
+ osc['port'] = name
+
+ message, deltatime = event
+ mtype = message[0] & 0xF0
+
+ if mtype in MIDI_TO_OSC:
+
+ osc['address'] = MIDI_TO_OSC[mtype]
+
+ if mtype == SYSTEM_EXCLUSIVE:
+ # Parse the provided data into a hex MIDI data string of the form 'f0 7e 7f 06 01 f7'.
+ v = ' '.join([hex(x).replace('0x', '').zfill(2) for x in message])
+ osc['args'].append({'type': 'string', 'value': v})
+
+ else:
+
+ status = message[0]
+ channel = (status & 0x0F) + 1
+
+ osc['args'].append({'type': 'i', 'value': channel})
+
+ if mtype == NOTE_OFF:
+ message[2] = 0
+
+ elif mtype == PITCH_BEND:
+ message = message[:1] + [message[1] + message[2] * 128] # convert 0-127 pair -> 0-16384 ->
+
+ elif mtype == PROGRAM_CHANGE and PROGRAM_CHANGE_OFFSET:
+ message[-1] = message[-1] + 1
+
+ for data in message[1:]:
+ osc['args'].append({'type': 'i', 'value': data})
+
+
+ if debug:
+ ipc_send('log','(DEBUG, MIDI) in: %s From: midi:%s' % (midi_str(message), name))
+
+ ipc_send('osc', osc)
+
+
+
+ def callback_error_wrapper(event, data):
+
+ try:
+ receive_midi(event, data)
+ except:
+ ipc_send('log', '(ERROR, MIDI) %s' % traceback.format_exc())
+
+ return callback_error_wrapper
+
+for name in inputs:
+
+ inputs[name].set_callback(create_callback(name))
+
+ # sysex / mtc support
+ ignore_sysex = 'sysex' not in argv
+ ignore_mtc = 'mtc' not in argv
+ inputs[name].ignore_types(ignore_sysex, ignore_mtc, True)
+
+
+def midi_message(status, channel, data1=None, data2=None):
+
+ msg = [(status & 0xF0) | (channel - 1 & 0x0F)]
+
+ if data1 != None:
+ msg.append(data1 & 0x7F)
+
+ if data2 != None:
+ msg.append(data2 & 0x7F)
+
+ return msg
+
+
+sysexRegex = re.compile(r'([^0-9A-Fa-f])\1(\1\1)*')
+
+def send_midi(name, event, *args):
+
+ if name not in outputs:
+ ipc_send('log','(ERROR, MIDI) unknown output (%s)' % name)
+ return
+
+ if event not in OSC_TO_MIDI:
+ ipc_send('log','(ERROR, MIDI) invalid address (%s)' % event)
+ return
+
+ m = None
+
+ mtype = OSC_TO_MIDI[event]
+
+ if mtype == SYSTEM_EXCLUSIVE:
+
+ try:
+ m = []
+ for arg in args:
+ if type(arg) is str:
+ arg = arg.split(' ')
+ arg = [int(x, 16) for x in arg]
+ for x in arg:
+ m.append(x)
+ else:
+ m.append(int(arg))
+
+ except:
+ pass
+
+ else:
+
+ args = [int(round(x)) for x in args]
+ m = [mtype, args[0]]
+
+ if mtype == NOTE_ON:
+ if args[2] == 0:
+ mtype = NOTE_OFF
+
+ elif mtype == PITCH_BEND:
+ args = args[:1] + [args[1] & 0x7F, (args[1] >> 7) & 0x7F] # convert 0-16384 -> 0-127 pair
+
+ elif mtype == PROGRAM_CHANGE and PROGRAM_CHANGE_OFFSET:
+ args[-1] = args[-1] - 1
+
+ m = midi_message(mtype, *args)
+
+ if m == None:
+
+ ipc_send('log','(ERROR, MIDI) could not convert osc to midi (%s %s)' % (event, " ".join([str(x) for x in args])))
+
+ else:
+
+ outputs[name].send_message(m)
+
+ if debug:
+ ipc_send('log','(DEBUG, MIDI) out: %s To: midi:%s' % (midi_str(m), name))
+
+
+while True:
+
+ try:
+ msg = raw_input()
+ except:
+ break
+
+ try:
+ msg = JSON.loads(msg)
+ msg[1] = msg[1].lower()
+ send_midi(*msg)
+ except:
+ ipc_send('log', '(ERROR, MIDI) %s' % traceback.format_exc())
diff --git a/src/python/requirements.txt b/src/python/requirements.txt
new file mode 100644
index 00000000..3aa7f400
--- /dev/null
+++ b/src/python/requirements.txt
@@ -0,0 +1 @@
+python-rtmidi == 1.4.2
diff --git a/src/python/utils.py b/src/python/utils.py
new file mode 100644
index 00000000..56fde861
--- /dev/null
+++ b/src/python/utils.py
@@ -0,0 +1,59 @@
+from head import *
+
+MIDI_TO_OSC = {
+ NOTE_ON: '/note',
+ NOTE_OFF: '/note',
+ CONTROL_CHANGE: '/control',
+ PROGRAM_CHANGE: '/program',
+ PITCH_BEND: '/pitch',
+ SYSTEM_EXCLUSIVE: '/sysex',
+ CHANNEL_PRESSURE: '/channel_pressure',
+ POLY_PRESSURE: '/key_pressure'
+}
+
+OSC_TO_MIDI = {
+ '/note': NOTE_ON,
+ '/control': CONTROL_CHANGE,
+ '/program': PROGRAM_CHANGE,
+ '/pitch': PITCH_BEND,
+ '/sysex': SYSTEM_EXCLUSIVE,
+ '/channel_pressure': CHANNEL_PRESSURE,
+ '/key_pressure': POLY_PRESSURE
+}
+
+def midi_str(message):
+
+ mtype = message[0] & 0xF0
+ s = 'UNKNOWN'
+
+ if mtype == SYSTEM_EXCLUSIVE:
+
+ s = 'SYSTEM_EXCLUSIVE: sysex=%s' % ' '.join([hex(x).replace('0x', '').zfill(2) for x in message])
+
+ else:
+
+ status = message[0]
+ channel = (status & 0x0F) + 1
+
+ try:
+
+ if mtype == NOTE_ON:
+ s = 'NOTE_ON: channel=%i, note=%i, velocity=%i' % (channel, message[1], message[2])
+ elif mtype == NOTE_OFF:
+ s = 'NOTE_OFF: channel=%i, note=%i' % (channel, message[1])
+ elif mtype == CONTROL_CHANGE:
+ s = 'CONTROL_CHANGE: channel=%i, cc=%i, value=%i'% (channel, message[1], message[2])
+ elif mtype == PROGRAM_CHANGE:
+ s = 'PROGRAM_CHANGE: channel=%i, program=%i' % (channel, message[1])
+ elif mtype == PITCH_BEND:
+ s = 'PITCH_BEND: channel=%i, pitch=%i' % (channel, message[1] + message[2] * 128 if len(message) == 3 else message[1])
+ elif mtype == CHANNEL_PRESSURE:
+ s = 'CHANNEL_PRESSURE: channel=%i, pressure=%i' % (channel, message[1])
+ elif mtype == POLY_PRESSURE:
+ s = 'KEY_PRESSURE: channel=%i, note=%i, pressure=%i' % (channel, message[1], message[2])
+
+ except IndexError:
+
+ s = 'NONE (ERROR: wrong number of argument for %s)' % MIDI_TO_OSC[mtype]
+
+ return s
diff --git a/src/scss/colors/nord.scss b/src/scss/colors/nord.scss
new file mode 100644
index 00000000..488b8fa4
--- /dev/null
+++ b/src/scss/colors/nord.scss
@@ -0,0 +1,235 @@
+// Copyright (c) 2016-present Arctic Ice Studio
+// Copyright (c) 2016-present Sven Greb
+
+// Project: Nord
+// Version: 0.2.0
+// Repository: https://github.com/arcticicestudio/nord
+// License: MIT
+// References:
+// http://sass-lang.com
+// http://sassdoc.com
+
+////
+/// An arctic, north-bluish color palette.
+/// Created for the clean- and minimal flat design pattern to achieve a optimal focus and readability for code syntax
+/// highlighting and UI.
+/// It consists of a total of sixteen, carefully selected, dimmed pastel colors for a eye-comfortable, but yet colorful
+/// ambiance.
+///
+/// @author Arctic Ice Studio
+////
+
+/// Base component color of "Polar Night".
+///
+/// Used for texts, backgrounds, carets and structuring characters like curly- and square brackets.
+///
+/// @access public
+/// @example scss - SCSS
+/// /* For dark ambiance themes */
+/// .background {
+/// background-color: $nord0;
+/// }
+/// /* For light ambiance themes */
+/// .text {
+/// color: $nord0;
+/// }
+/// @group polarnight
+/// @since 0.1.0
+$nord0: #2e3440;
+
+/// Lighter shade color of the base component color.
+///
+/// Used as a lighter background color for UI elements like status bars.
+///
+/// @access public
+/// @group polarnight
+/// @see $nord0
+/// @since 0.1.0
+$nord1: #3b4252;
+
+/// Lighter shade color of the base component color.
+///
+/// Used as line highlighting in the editor.
+/// In the UI scope it may be used as selection- and highlight color.
+///
+/// @access public
+/// @example scss - SCSS
+/// /* Code Syntax Highlighting scope */
+/// .editor {
+/// &.line {
+/// background-color: $nord2;
+/// }
+/// }
+///
+/// /* UI scope */
+/// button {
+/// &:selected {
+/// background-color: $nord2;
+/// }
+/// }
+/// @group polarnight
+/// @see $nord0
+/// @since 0.1.0
+$nord2: #434c5e;
+
+/// Lighter shade color of the base component color.
+///
+/// Used for comments, invisibles, indent- and wrap guide marker.
+/// In the UI scope used as pseudoclass color for disabled elements.
+///
+/// @access public
+/// @example scss - SCSS
+/// /* Code Syntax Highlighting scope */
+/// .editor {
+/// &.indent-guide,
+/// &.wrap-guide {
+/// &.marker {
+/// color: $nord3;
+/// }
+/// }
+/// }
+/// .comment,
+/// .invisible {
+/// color: $nord3;
+/// }
+///
+/// /* UI scope */
+/// button {
+/// &:disabled {
+/// background-color: $nord3;
+/// }
+/// }
+/// @group polarnight
+/// @see $nord0
+/// @since 0.1.0
+$nord3: #4c566a;
+
+/// Base component color of "Snow Storm".
+///
+/// Main color for text, variables, constants and attributes.
+/// In the UI scope used as semi-light background depending on the theme shading design.
+///
+/// @access public
+/// @example scss - SCSS
+/// /* For light ambiance themes */
+/// .background {
+/// background-color: $nord4;
+/// }
+/// /* For dark ambiance themes */
+/// .text {
+/// color: $nord4;
+/// }
+/// @group snowstorm
+/// @since 0.1.0
+$nord4: #d8dee9;
+
+/// Lighter shade color of the base component color.
+///
+/// Used as a lighter background color for UI elements like status bars.
+/// Used as semi-light background depending on the theme shading design.
+///
+/// @access public
+/// @group snowstorm
+/// @see $nord4
+/// @since 0.1.0
+$nord5: #e5e9f0;
+
+/// Lighter shade color of the base component color.
+///
+/// Used for punctuations, carets and structuring characters like curly- and square brackets.
+/// In the UI scope used as background, selection- and highlight color depending on the theme shading design.
+///
+/// @access public
+/// @group snowstorm
+/// @see $nord4
+/// @since 0.1.0
+$nord6: #eceff4;
+
+/// Bluish core color.
+///
+/// Used for classes, types and documentation tags.
+///
+/// @access public
+/// @group frost
+/// @since 0.1.0
+$nord7: #8fbcbb;
+
+/// Bluish core accent color.
+///
+/// Represents the accent color of the color palette.
+/// Main color for primary UI elements and methods/functions.
+///
+/// Can be used for
+/// - Markup quotes
+/// - Markup link URLs
+///
+/// @access public
+/// @group frost
+/// @since 0.1.0
+$nord8: #88c0d0;
+
+/// Bluish core color.
+///
+/// Used for language-specific syntactic/reserved support characters and keywords, operators, tags, units and
+/// punctuations like (semi)colons,commas and braces.
+///
+/// @access public
+/// @group frost
+/// @since 0.1.0
+$nord9: #81a1c1;
+
+/// Bluish core color.
+///
+/// Used for markup doctypes, import/include/require statements, pre-processor statements and at-rules (`@`).
+///
+/// @access public
+/// @group frost
+/// @since 0.1.0
+$nord10: #5e81ac;
+
+/// Colorful component color.
+///
+/// Used for errors, git/diff deletion and linter marker.
+///
+/// @access public
+/// @group aurora
+/// @since 0.1.0
+$nord11: #bf616a;
+
+/// Colorful component color.
+///
+/// Used for annotations.
+///
+/// @access public
+/// @group aurora
+/// @since 0.1.0
+$nord12: #d08770;
+
+/// Colorful component color.
+///
+/// Used for escape characters, regular expressions and markup entities.
+/// In the UI scope used for warnings and git/diff renamings.
+///
+/// @access public
+/// @group aurora
+/// @since 0.1.0
+$nord13: #ebcb8b;
+
+/// Colorful component color.
+///
+/// Main color for strings and attribute values.
+/// In the UI scope used for git/diff additions and success visualizations.
+///
+/// @access public
+/// @group aurora
+/// @since 0.1.0
+$nord14: #a3be8c;
+
+/// Colorful component color.
+///
+/// Used for numbers.
+///
+/// @access public
+/// @group aurora
+/// @since 0.1.0
+$nord15: #b48ead;
diff --git a/src/scss/index.scss b/src/scss/index.scss
new file mode 100644
index 00000000..f2d6d59c
--- /dev/null
+++ b/src/scss/index.scss
@@ -0,0 +1,99 @@
+@import 'reset';
+@import 'mixins';
+@import 'themes/default';
+@import 'ui';
+@import 'widgets';
+
+
+input,
+textarea,
+{
+ caret-color: var(--color-widget);
+}
+
+input:focus::selection,
+textarea:focus::selection,
+{
+ background:var(--color-widget);
+ color: var(--color-text);
+}
+input {
+ cursor: text;
+}
+
+
+
+
+.fa {
+ font-weight: 900;
+}
+
+html, body {
+
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+
+ overflow:hidden;
+ overscroll-behavior: none;
+ background-color: var(--color-background);
+}
+
+html{
+ // global pixel scaling
+ font-size: 1px;
+
+ // prevent android's auto font-resize
+ max-height: 999999px;
+
+ // prevent pinch-zoom
+ touch-action:none;
+}
+
+body {
+ color: var(--color-text);
+ white-space:nowrap;
+ opacity:1;
+ cursor: default;
+ font-family: $font;
+ font-size:11rem;
+ line-height:100%;
+ font-weight: 500;
+ // text-transform: uppercase;
+ letter-spacing: 1rem;
+ text-rendering: optimizeSpeed;
+
+}
+
+
+.error-stack {
+ > span {
+ background: none!important;
+ color: inherit!important;
+ }
+ padding:10rem;
+ user-select:initial;
+ cursor: initial;
+ * {
+ user-select:initial;
+ cursor: initial;
+ }
+ overflow:auto;
+ white-space:pre;
+ font-family: $font-mono;
+ font-weight:bold;
+}
+
+.translation-missing {
+ color: #ff00ff;
+}
+
+.fa-osc:before {
+ content:"\f111";
+ color: transparent;
+ background-image: url(../assets/favicon.png);
+ background-size: contain;
+ background-repeat: no-repeat;
+}
diff --git a/src/scss/mixins.scss b/src/scss/mixins.scss
new file mode 100644
index 00000000..5de3094e
--- /dev/null
+++ b/src/scss/mixins.scss
@@ -0,0 +1,32 @@
+@mixin pseudo-stroke($z: 0) {
+ &:before {
+ content:"";
+ position: absolute;
+ border: var(--line-width) solid var(--color-stroke);
+ opacity: var(--alpha-stroke);
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ pointer-events: none;
+ z-index: $z;
+ border-radius: inherit;
+ }
+}
+
+@mixin pseudo-fill($z: 0) {
+ &:after {
+ content:"";
+ position: absolute;
+ background: var(--color-fill);
+ opacity: var(--alpha-fill);
+ top: var(--line-width);
+ left: var(--line-width);
+ right: var(--line-width);
+ bottom: var(--line-width);
+ pointer-events: none;
+ margin: var(--widget-padding);
+ z-index: $z;
+ border-radius: inherit;
+ }
+}
diff --git a/src/browser/scss/_reset.scss b/src/scss/reset.scss
similarity index 74%
rename from src/browser/scss/_reset.scss
rename to src/scss/reset.scss
index ba991012..d4d9a88a 100644
--- a/src/browser/scss/_reset.scss
+++ b/src/scss/reset.scss
@@ -14,3 +14,10 @@
-moz-user-select: none;
user-select: none;
}
+
+
+select, input, textarea {
+ -webkit-appearance:none;
+ -moz-appearance:none;
+ appearance:none;
+}
diff --git a/src/scss/themes/default.scss b/src/scss/themes/default.scss
new file mode 100644
index 00000000..66fa786e
--- /dev/null
+++ b/src/scss/themes/default.scss
@@ -0,0 +1,42 @@
+$font: 'Roboto';
+$font-mono: 'Roboto Mono';
+$font-menu: sans-serif;
+
+
+@import '../colors/nord';
+
+:root {
+
+ --nav-height: 40rem;
+ --grid-width: 10;
+
+
+ --color-background: #21252b;
+ --color-ui-background: #2c313a;
+ --color-ui-button: #{$nord1};
+ --color-accent: #6db5fd;
+
+ --color-text: #{$nord4};
+ --color-text-solid: #{$nord6};
+
+
+ --color-accent: #6db5fd;
+ --color-error: #{$nord11};
+ --color-warning: #{$nord13};
+ --color-success: #{$nord14};
+
+ --color-context-menu: #{$nord6};
+ --color-context-menu-text: #{$nord1};
+
+
+ --line-width: 1rem;
+
+ --alpha-scrollbar: 0.25;
+ --alpha-scrollbar-on: 0.75;
+ --scrollbar-size: 12rem;
+
+ --color-grid: rgba(0,0,0, 0.1);
+ --color-notification: #{rgba(black, 0.8)};
+ --color-widget: var(--color-accent);
+
+}
diff --git a/src/scss/themes/nord.scss b/src/scss/themes/nord.scss
new file mode 100644
index 00000000..f9afb9f6
--- /dev/null
+++ b/src/scss/themes/nord.scss
@@ -0,0 +1,8 @@
+@import 'default';
+
+:root {
+ --color-background: #{$nord0};
+ --color-ui-background: #{$nord1};
+ --color-ui-button: #{$nord3};
+ --color-accent: #{$nord8};
+}
diff --git a/src/scss/themes/orange.scss b/src/scss/themes/orange.scss
new file mode 100644
index 00000000..bb52f76f
--- /dev/null
+++ b/src/scss/themes/orange.scss
@@ -0,0 +1,8 @@
+@import 'default';
+
+:root {
+ --color-background: #404040;
+ --color-ui-background: #505050;
+ --color-ui-button: #606060;
+ --color-accent: #d98533;
+}
diff --git a/src/scss/ui.scss b/src/scss/ui.scss
new file mode 100644
index 00000000..6b08170c
--- /dev/null
+++ b/src/scss/ui.scss
@@ -0,0 +1,15 @@
+@import 'ui/button';
+@import 'ui/scrollbars';
+@import 'ui/workspaces';
+@import 'ui/notifications';
+@import 'ui/grid';
+@import 'ui/inspector';
+@import 'ui/tree';
+@import 'ui/dragresize';
+@import 'ui/selectarea';
+@import 'ui/contextmenu';
+@import 'ui/modal';
+@import 'ui/filebrowser';
+@import 'ui/loading';
+@import 'ui/toolbar';
+@import 'ui/launcher';
diff --git a/src/scss/ui/button.scss b/src/scss/ui/button.scss
new file mode 100644
index 00000000..409076c7
--- /dev/null
+++ b/src/scss/ui/button.scss
@@ -0,0 +1,15 @@
+.btn {
+ background: var(--color-background);
+ display: block;
+ padding: 0 15rem;
+ position: relative;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ text-align: center;
+ cursor: pointer;
+ &.disabled {
+ pointer-events: none;
+ opacity: 0.5;
+ }
+}
diff --git a/src/scss/ui/contextmenu.scss b/src/scss/ui/contextmenu.scss
new file mode 100644
index 00000000..b4c4e3f4
--- /dev/null
+++ b/src/scss/ui/contextmenu.scss
@@ -0,0 +1,114 @@
+$line-height: 30rem;
+
+.context-menu {
+
+ --widget-padding: 0rem;
+ --alpha-fill: 1;
+
+ position:fixed;
+ z-index: 9999999;
+ background: var(--color-context-menu);
+ box-shadow: 0 0 0 0.5rem rgba(0, 0, 0, 0.15) inset;
+ text-transform: none;
+ color: var(--color-context-menu-text);
+ font-weight: 500;
+ font-size: 13rem;
+ line-height: $line-height;
+ font-family: $font-menu;
+ letter-spacing: normal;
+ padding-top: 3rem;
+ padding-bottom: 3rem;
+
+ .context-menu {
+ position: absolute;
+ left:100%;
+ top:-3rem;
+ opacity:0;
+ pointer-events: none;
+ margin-left: -1rem;
+ &:before {
+ content:"";
+ position: absolute;
+ top:0;
+ bottom:0;
+ left:-2rem;
+ width:2rem;
+ }
+ }
+ > .item {
+ padding-left: 30rem;
+ padding-right: 30rem;
+ position:relative;
+ cursor: pointer;
+ display: flex;
+ flex-direction: row;
+ i {
+ position: absolute;
+ left: 10rem;
+ width: 10rem;
+ text-align: center;
+ line-height: $line-height - 2;
+ font-size: 9rem;
+ pointer-events: none;
+ }
+ &.focus {
+ > .context-menu {
+ pointer-events: auto;
+ opacity: 1;
+ }
+ @include pseudo-fill($z: -1);
+ color: var(--color-context-menu);
+ }
+ &.has-sub:before {
+ content:"\f105";
+ display: block;
+ font-family: FontAwesome;
+ text-align: right;
+ margin-right: -20rem;
+ position: relative;
+ flex: 1;
+ order: 1;
+ margin-left: 10rem;
+ }
+ &.disabled {
+ pointer-events: none;
+ opacity: 0.5;
+ }
+ &.toggle:before {
+ content: "";
+ display: block;
+ font-family: FontAwesome;
+ position: absolute;
+ width: 10rem;
+ height: 10rem;
+ left: 10rem;
+ top: 8rem;
+ border: 1rem solid;
+ opacity: 0.75;
+ line-height: 10rem;
+ font-size: 8rem;
+ text-align: right;
+ }
+ &.toggle.on:before {
+ content:"\f00c";
+ }
+ .shortcut {
+ display: inline-block;
+ margin-left: 20rem;
+ margin-right: -20rem;
+ position: relative;
+ text-align: right;
+ position: relative;
+ flex: 1;
+ text-transform: capitalize;
+ opacity: 0.5;
+ pointer-events: none;
+ }
+ }
+ .separator{
+ margin: 2rem 1rem;
+ height: 1rem;
+ background-color: var(--color-context-menu-text);
+ opacity: 0.15;
+ }
+}
diff --git a/src/scss/ui/dragresize.scss b/src/scss/ui/dragresize.scss
new file mode 100644
index 00000000..ad8d57ca
--- /dev/null
+++ b/src/scss/ui/dragresize.scss
@@ -0,0 +1,91 @@
+#drag-resize {
+
+ --color-fill: var(--color-accent);
+ --color-stroke: var(--color-accent);
+
+ position: absolute;
+ z-index: 99999999;
+
+ top: var(--top);
+ left: var(--left);
+
+ &:before {
+ content:"";
+ position: absolute;
+ top:0;left:0;
+ width: calc(var(--width) - 2rem);
+ height: calc(var(--height) - 2rem);
+ border: 1rem solid var(--color-accent);
+ opacity: 0.2;
+ pointer-events: none;
+ }
+
+ .helper {
+
+ position: absolute;
+ top:0;
+ left:0;
+ width: var(--width);
+ height: var(--height);
+ pointer-events: none;
+ --alpha-fill: 0.5;
+ --widget-padding: -1rem;
+ opacity: 0.5;
+ display: none;
+ border: 1rem solid var(--color-stroke);
+ @include pseudo-fill();
+ }
+
+ &.dragging .helper {
+ display: block;
+ }
+
+ .handle {
+
+ $size: 10rem;
+
+ position: absolute;
+ background: var(--color-fill);
+ width: $size;
+ height: $size;
+ border: 2rem solid transparent;
+ background-clip: content-box;
+ // opacity: 0.75;
+
+ &.nw {
+ cursor: move;
+ }
+
+ &.e {
+
+ top: calc(var(--height) / 2);
+ left: var(--width);
+ margin-left: -$size;
+ margin-top: -$size / 2;
+ cursor: e-resize;
+
+ }
+
+ &.se {
+
+ top: var(--height);
+ left: var(--width);
+ margin-left: -$size;
+ margin-top: -$size;
+ cursor: se-resize;
+
+ }
+
+ &.s {
+
+ top: var(--height);
+ left: calc(var(--width) / 2);
+ margin-left: -$size / 2;
+ margin-top: -$size;
+ cursor: s-resize;
+
+ }
+
+ }
+
+}
diff --git a/src/scss/ui/filebrowser.scss b/src/scss/ui/filebrowser.scss
new file mode 100644
index 00000000..b04a1f42
--- /dev/null
+++ b/src/scss/ui/filebrowser.scss
@@ -0,0 +1,96 @@
+$padding: 8rem;
+
+.file-browser {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+
+
+ .ariane {
+ height: 40rem;
+ flex-shrink: 0;
+ line-height: 40rem;
+ padding-left: $padding + 2rem;
+ background: var(--color-ui-button);
+
+ }
+ .file-list {
+ overflow-y: auto;
+ flex:1;
+ background: var(--color-background);
+ padding: 0 $padding;
+ margin: 1rem 0;
+ }
+ .file {
+ position: relative;
+ height: 40rem;
+ line-height: 40rem;
+ input {
+ position: absolute;
+ width:100%;
+ height: 100%;
+ opacity: 0;
+ cursor: pointer;
+ }
+ .label {
+ position: absolute;
+ width:100%;
+ height: 100%;
+ pointer-events: none;
+ white-space: nowrap;
+ span {
+ display: block;
+ width: 100%;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ }
+ }
+ input:checked + .label {
+ color: var(--color-widget);
+ &:before {
+ content:"";
+ position: absolute;
+ left:-$padding;
+ right:-$padding;
+ height: 100%;
+ background: var(--color-widget);
+ opacity: 0.1;
+ }
+ }
+ }
+ .file-actions {
+ display: flex;
+ flex-direction: row;
+ align-items: flex-end;
+ justify-content: stretch;
+ height: 42rem + $padding * 2;
+ line-height: 38rem;
+ flex-shrink: 0;
+ // border: $padding solid var(--color-ui-background);
+ padding: $padding;
+ background: var(--color-ui-background);
+ .btn {
+ margin: 1rem;
+ margin-left: $padding;
+ text-overflow: clip;
+ min-width: 0;
+ background: var(--color-ui-button);
+ }
+ i {
+ pointer-events: none;
+ }
+ .save-as {
+ flex:1;
+ border: 0;
+ margin: 1rem;
+ padding: 0 10rem;
+ font-size: 120%;
+ position: relative;
+ background: var(--color-background);
+ min-width: 0;
+ &[disabled] {
+ visibility: hidden;
+ }
+ }
+ }
+}
diff --git a/src/scss/ui/grid.scss b/src/scss/ui/grid.scss
new file mode 100644
index 00000000..112a4bc4
--- /dev/null
+++ b/src/scss/ui/grid.scss
@@ -0,0 +1,22 @@
+.editor-enabled {
+ &:not(.no-grid) {
+ .root-container,
+ .tab-container,
+ .modal-container,
+ .panel-container {
+ > inner {
+ background-image: linear-gradient(to bottom, var(--color-grid) 1rem, transparent 1rem),
+ linear-gradient(to right, var(--color-grid) 1rem, transparent 1rem);
+ --size: calc(var(--grid-width) * 1rem);
+ background-size: var(--size) var(--size);
+ background-attachment: local;
+ background-position: 0rem 0;
+ }
+ }
+ }
+
+ .widget:not(.not-editable) {
+ pointer-events: initial!important;
+ }
+
+}
diff --git a/src/scss/ui/inspector.scss b/src/scss/ui/inspector.scss
new file mode 100644
index 00000000..09a000e5
--- /dev/null
+++ b/src/scss/ui/inspector.scss
@@ -0,0 +1,374 @@
+$header-height: 28rem;
+$field-height: 24rem;
+$padding: 8rem;
+
+#osc-inspector {
+
+ --widget-padding: -1rem;
+
+}
+
+osc-inspector-field {
+
+ display: flex;
+ flex-direction: row;
+ line-height: $field-height;
+ margin-top: 2rem;
+ position: relative;
+
+ --widget-padding: -1rem;
+
+
+ label {
+ width: 90rem;
+ // order: 35;
+ text-align: right;
+ text-transform: none;
+ padding-right: 8rem;
+ line-height: $field-height + 1rem;
+ height: $field-height;
+ cursor: help;
+ // background: rgba(white, 0.1);
+ }
+
+ textarea, input {
+ font-family: $font-mono;
+
+ line-height: $field-height - 8rem;
+ padding: 4rem 6rem;
+ flex: 1;
+ overflow-x: auto;
+ overflow-y: hidden;
+ resize: none;
+ white-space: pre;
+ display: block;
+ background: var(--color-background);
+ cursor: text;
+
+ user-select: initial;
+
+ --scrollbar-size: 6rem;
+
+ // Chromium scrollbar
+ &::-webkit-scrollbar-thumb:horizontal {
+ cursor: normal;
+ }
+
+ // Firefox scrollbar (hidden to preserve height)
+ scrollbar-width: thin;
+ &[rows="1"] {
+ scrollbar-width: none;
+ }
+
+
+ }
+
+
+ .computed-value {
+ position: absolute;
+ right: 4rem;
+ text-align: right;
+ pointer-events: none;
+ opacity: 0.5;
+ font-style: italic;
+ margin-top: 1rem;
+ }
+
+}
+
+
+osc-inspector-category {
+
+ margin-top: 1rem;
+ display: block;
+ padding: 0 8rem;
+
+ &:first-child {
+ margin-top: 0
+ }
+
+ .category-header {
+ position: relative;
+ cursor: pointer;
+ height: $header-height;
+ line-height: $header-height;
+ // padding: 0 8rem;
+ @include pseudo-fill($z: -1);
+
+ &:after {
+ left:-($padding - 1);
+ right:-($padding - 1);
+ }
+
+ &:before {
+ position: relative;
+ font-family: FontAwesome;
+ content: "\f054";
+ width: $field-height;
+ text-align: left;
+ display: inline-block;
+ transform-origin: 2rem 3rem;
+ width: 8rem;
+ margin-right: 8rem;
+ }
+
+ }
+
+ .separator {
+ height: $header-height;
+ line-height: $header-height + 1;
+ margin: 8rem 0;
+ --alpha-fill: 0.75;
+ position: relative;
+ @include pseudo-fill($z: -1);
+ padding: 0 16rem;
+ opacity: 0.75;
+ --color-fill: var(--color-background);
+ &:after {
+ left:-($padding - 1);
+ right:-($padding - 1);
+ }
+ }
+
+ osc-inspector-field, .separator {
+ display: none;
+ }
+ --alpha-fill: 1;
+ --color-fill: var(--color-ui-button);
+
+ &.expanded {
+ // --alpha-fill: 1;
+ --alpha-fill: 0.5;
+ --color-fill: var(--color-widget);
+
+ .category-header:before {
+ content: "\f078";
+ }
+ osc-inspector-field {
+ display: flex;
+ }
+ .separator {
+ display: block
+ }
+ }
+
+ .category-header + osc-inspector-field {
+ margin-top: 8rem;
+ }
+ osc-inspector-field:last-child {
+ margin-bottom: 8rem;
+ }
+}
+
+
+osc-inspector-checkbox {
+
+ --widget-padding: 0;
+ --color-fill: var(--color-ui-button);
+ --alpha-fill: 1;
+
+ line-height: $field-height;
+ height: $field-height;
+ width: $field-height;
+ cursor: pointer;
+ background: var(--color-background);
+ text-align: center;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: 1rem solid var(--color-background);
+ i {
+ // color: transparent;
+ opacity: 0.5;
+ margin-top: -1rem;
+ margin-left: 1rem;
+ pointer-events: none;
+ font-size: 10rem;
+ }
+ position: relative;
+ @include pseudo-fill($z: -1);
+ z-index: 1;
+
+ &.on {
+ --color-fill: var(--color-widget);
+ --alpha-fill: 0.5;
+
+ i {
+ opacity: 1;
+ color: var(--color-text-solid);
+ }
+ }
+
+}
+
+osc-inspector-select {
+ position: relative;
+ font-family: $font-mono;
+ line-height: inherit;
+ padding: 0;
+ overflow: hidden;
+ height: $field-height;
+ width: $field-height;
+ background: var(--color-background);
+ cursor: pointer;
+
+ select {
+ background: var(--color-background);
+ // width: 100%;
+ line-height: $field-height - 8rem;
+ padding: 4rem 6rem;
+
+ position: absolute;
+ right:2rem;
+ width: 127rem;
+ opacity: 0;
+ optgroup {
+ background: var(--color-ui-background);
+ font-weight: bold;
+ option {
+ background: var(--color-background);
+ color: var(--color-text);
+ margin-left: -4rem;
+ font-weight: normal;
+ text-indent: -10px;
+ margin: 0;
+ }
+ }
+ }
+ &:after{
+ content:"\f107";
+ font-family: FontAwesome;
+ position: absolute;
+ line-height: $field-height;
+ height: $field-height;
+ width: $field-height;
+ text-align: center;
+ right:0;
+ top:1rem;
+ font-size: 16rem;
+ pointer-events: none;
+ }
+}
+
+
+osc-inspector-color {
+ padding: 0;
+ border: 0;
+ box-shadow: 0;
+ outline: 0;
+ position: relative;
+ font-family: $font-mono;
+ line-height: inherit;
+ overflow: hidden;
+ height: $field-height;
+ width: $field-height;
+ background: var(--color-background);
+
+ cursor: pointer;
+
+
+
+ --color-fill: var(--color-picker-value);
+ --alpha-fill: 1;
+ --widget-padding: 1rem;
+ @include pseudo-fill();
+ &:after {
+ border: 1rem solid var(--color-ui-button)
+ }
+}
+
+.color-picker-modal {
+
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+
+ .widget {
+ background: var(--color-background);
+ flex: 1;
+ width: auto;
+ --widget-padding: #{$padding};
+ }
+
+ .actions {
+ display: flex;
+ flex-direction: row;
+ align-items: flex-end;
+ justify-content: stretch;
+ height: 42rem + $padding * 2;
+ line-height: 38rem;
+ flex-shrink: 0;
+ background: var(--color-ui-background);
+ padding: $padding;
+ .btn {
+ flex: 1;
+ text-overflow: clip;
+ min-width: 0;
+ background: var(--color-ui-button);
+ margin-right: $padding;
+ &:last-child {
+ margin: 0;
+ }
+ }
+ }
+
+}
+
+.inspector-help {
+
+ width: 100%;
+ padding: 8rem;
+ background: var(--color-background);
+
+ p {
+ }
+ .error {
+ color: red;
+ margin-top: 10rem;
+ }
+ em {
+ font-style: italic;
+ }
+ code {
+ color: var(--color-accent);
+ padding: 4rem;
+ background: rgba(black, 0.2);
+ display: inline-block;
+ user-select: auto;
+ cursor: auto;
+ ::selection{/* reset */}
+ }
+ a {
+ text-decoration: underline;
+ cursor: pointer;
+ }
+ .pre {
+ white-space: pre;
+ vertical-align: text-top;
+ margin-top: -4rem;
+ position: relative;
+ padding: 5rem;
+ user-select: text;
+ }
+
+ .header p {
+ margin-bottom: 2rem;
+ user-select: text;
+ }
+ .description {
+ border-top: 2rem solid var(--color-ui-background);
+ margin-top: 10rem;
+ padding-top: 10rem;
+ white-space: normal;
+ * {
+ user-select: text;
+ }
+ }
+
+ .computed {
+ border-top: 2rem solid var(--color-ui-background);
+ margin-top: 10rem;
+ padding-top: 10rem;
+
+ }
+}
diff --git a/src/scss/ui/launcher.scss b/src/scss/ui/launcher.scss
new file mode 100644
index 00000000..1a6ab0bd
--- /dev/null
+++ b/src/scss/ui/launcher.scss
@@ -0,0 +1,194 @@
+#osc-launcher {
+
+ osc-panel-header {
+ background-color: var(--color-ui-background);
+ --alpha-fill: .75;
+ text-align: left;
+ justify-content: center;
+ .spacer {
+ flex: 1;
+ }
+ span {
+ opacity: 0.5;
+ position: absolute;
+ right: 12rem;
+ }
+ flex-shrink: 0;
+ }
+
+ flex-direction: column;
+
+ osc-panel-container.main {
+ background-color: var(--color-ui-background);
+ min-height: 0;
+ min-height: 40rem;
+ osc-panel-content {
+ padding: 8rem;
+ background-color: var(--color-ui-background);
+ }
+ }
+ osc-panel-content {
+ overflow-y: auto;
+ flex: 1;
+ }
+
+ osc-panel-container.bottom {
+ flex: 1;
+ padding: 12rem 8rem;
+ min-height: 100rem;
+
+ &.minimized {
+ padding: 0;
+ }
+
+ border-top: 2rem solid var(--color-ui-background);
+ max-height: calc(100% - var(--nav-height));
+ background-color: var(--color-background);
+ osc-panel-inner {
+ background-color: var(--color-background);
+ }
+
+ // --color-background: --color-ui-background; // scrollbar
+ }
+
+ osc-panel-inner {
+ contain: layout style;
+ }
+
+}
+
+osc-settings {
+
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+
+}
+osc-settings-field {
+ display: flex;
+ flex-direction: row;
+ margin: 1rem;
+ line-height: 22rem;
+ position: relative;
+ label {
+ width: 100rem;
+ text-align: right;
+ margin-right: 8rem;
+ position: relative;
+ line-height: 24rem;
+ height: 22rem;
+ cursor: help;
+ span {
+ opacity: 0.5;
+ }
+ }
+ input {
+ appearance: none;
+ background: var(--color-background);
+ flex: 1;
+ padding: 0 4rem;
+ width: 100rem;
+ }
+ [disabled], [disabled] ~ * {
+ pointer-events: none;
+ opacity: 0.75!important;
+
+ }
+
+ &.error label {
+ color: var(--color-error);
+ }
+ &.restart label:after {
+ content: "";
+ position: absolute;
+ top:1rem;
+ left:4rem;
+ right:-4rem;
+ bottom:0;
+ background: var(--color-warning);
+ opacity: 0.25;
+ border-radius: 4rem;
+ }
+}
+
+osc-settings-checkbox, osc-settings-reset, osc-settings-file {
+ @extend osc-inspector-checkbox;
+
+ i {
+ color: var(--color-text);
+ opacity: 0.75;
+ }
+ &:hover i {
+ opacity: 1;
+ }
+ &.on {
+ --alpha-fill: 0.5;
+ i {
+ color: var(--color-text-solid);
+ opacity: 1;
+ }
+ }
+ &:last-child {
+ margin-left: -1rem;
+ border-left: 0;
+ }
+}
+
+#osc-terminal {
+ flex: 1;
+ line-height: 18rem;
+ user-select:text;
+ cursor: auto;
+
+ > div {
+ margin: 0 12rem 4rem;
+ }
+
+
+ * {
+ user-select:text;
+ cursor: auto;
+ white-space: pre-wrap;
+ }
+
+ .help {
+ font-style: italic;
+ color: var(--color-accent);
+ }
+
+ .warning {
+ color: var(--color-warning);
+ }
+
+ .error {
+ color: var(--color-error);
+ }
+
+ .trace {
+ position: relative;
+ height: 18rem;
+ overflow: hidden;
+ &.show {
+ height: auto;
+ .trace-button:before {
+ content: "\f078";
+ }
+ }
+ }
+ .trace-button {
+ &:before {
+ content: "\f054";
+ font-size: 10rem;
+ font-family: FontAwesome;
+ }
+ position: absolute;
+ left: 0;
+ margin-top: -1rem;
+ cursor: pointer;
+ user-select: none;
+ }
+
+ a {
+ text-decoration: underline;
+ cursor: pointer;
+ }
+}
diff --git a/src/scss/ui/loading.scss b/src/scss/ui/loading.scss
new file mode 100644
index 00000000..ed10dc4b
--- /dev/null
+++ b/src/scss/ui/loading.scss
@@ -0,0 +1,39 @@
+
+#loading {
+ position: fixed;
+ top:50%;
+ left:50%;
+ margin-left:-15rem;
+ margin-top:-15rem;
+ text-align: center;
+}
+
+.spinner {
+ display: block;
+ margin: 0 auto;
+ height:36rem;
+ width:36rem;
+ border-radius: 50%;
+ position: relative;
+ margin: 20rem auto;
+
+
+ &:after {
+ content:"";
+ position: absolute;
+ left:-3rem;
+ top:-3rem;
+ right:-3rem;
+ bottom:-3rem;
+ border:4rem solid var(--color-ui-background);
+ border-top: 2rem solid var(--color-widget);
+ transform: rotateZ(0deg);
+ animation: spin .5s linear infinite;
+ border-radius: 50%;
+ }
+}
+
+@keyframes spin {
+ 0% {transform: rotateZ(0deg);}
+ 100% {transform: rotateZ(360deg);}
+}
diff --git a/src/scss/ui/modal.scss b/src/scss/ui/modal.scss
new file mode 100644
index 00000000..b16a8adc
--- /dev/null
+++ b/src/scss/ui/modal.scss
@@ -0,0 +1,109 @@
+$padding: 8rem;
+
+@keyframes popup-backdrop-fade-in {
+ 0% {opacity: 0}
+ 100% {opacity: .03}
+}
+
+.popup {
+
+ &:before {
+
+ content: "";
+ position: fixed;
+ top:0rem;
+ left:0;
+ right:0;
+ bottom:0;
+ background: black;
+ opacity: .3;
+ pointer-events: none;
+ // animation: popup-backdrop-fade-in .25s forwards;
+
+ }
+
+ // backdrop-filter: blur(1rem);
+
+ position: fixed;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ align-items:center;
+ justify-content: center;
+ z-index: 99999999;
+ display: none;
+ padding: 20rem;
+
+ &.show {
+ display: flex;
+ }
+
+ .popup-title {
+ position: relative;
+ min-height: var(--nav-height);
+ height: var(--nav-height);
+ display: flex;
+ padding:0 $padding * 2 - 1;
+ align-items: center;
+ background: var(--color-ui-background);
+ .title {
+ flex:1;
+ overflow: hidden;
+ }
+ > i {
+ display: block;
+ margin-right: 10rem;
+ }
+ &.closable {
+ padding-right: 0;
+ }
+ .popup-label {
+ flex:1;
+ overflow: hidden;
+ }
+ .closer {
+ height: var(--nav-height);
+ width: var(--nav-height);
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ i {
+ pointer-events: none;
+ }
+ }
+ }
+ .popup-wrapper {
+ background: var(--color-background);
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ width:auto;
+ position: relative;
+ overflow: hidden;
+
+ max-width: 100%;
+ max-height: 100%;
+ width: var(--width, 540rem);
+ height: var(--height, auto);
+
+ .popup-content {
+ flex:1;
+ width: auto;
+ // padding: 2rem $padding $padding;
+ min-height: 0;
+ display: flex;
+ }
+
+ .message {
+ white-space: normal;
+ line-height: 150%;
+ background: var(--color-background);
+ padding: $padding;
+ overflow-x: auto;
+ }
+
+ }
+}
diff --git a/src/scss/ui/notifications.scss b/src/scss/ui/notifications.scss
new file mode 100644
index 00000000..b9393516
--- /dev/null
+++ b/src/scss/ui/notifications.scss
@@ -0,0 +1,57 @@
+#notifications {
+ position: fixed;
+ bottom:0;
+ right:0;
+ display: flex;
+ flex-direction: column-reverse;
+ z-index: 9999999;
+ padding:10rem;
+ width:300rem;
+ &:empty {
+ display: none;
+ }
+ .toast {
+ animation: toast_fade-in 0.2s forwards;
+ transform-origin: bottom;
+ background: var(--color-notification);
+ transition: all 0.2s;
+ overflow: hidden;
+ margin-top: 10rem;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ &.remove {
+ animation: toast_fade-out 0.2s forwards;
+ height: 0!important;
+ margin-top: 0!important;
+ }
+ i {
+ margin-left: 10rem;
+ font-size: 14rem;
+ min-width: 30rem;
+ color: var(--color-accent);
+ }
+ &.error {
+ i {
+ color: red;
+ }
+ }
+ .content {
+ padding: 10rem;
+ white-space: pre-line;
+ text-transform: none;
+ line-height: normal;
+ }
+ }
+
+}
+
+@keyframes toast_fade-in {
+ from {opacity: 0; transform: rotateX(90deg)}
+ to {opacity: 1; transform: rotateX(0)}
+}
+
+@keyframes toast_fade-out {
+ from {opacity: 1; transform: rotateX(0)}
+ to {opacity: 0; transform: rotateX(90deg)}
+}
diff --git a/src/scss/ui/scrollbars.scss b/src/scss/ui/scrollbars.scss
new file mode 100644
index 00000000..ce14aa62
--- /dev/null
+++ b/src/scss/ui/scrollbars.scss
@@ -0,0 +1,48 @@
+// Chromium
+
+::-webkit-scrollbar {
+ width: var(--scrollbar-size);
+ height:var(--scrollbar-size);
+}
+
+::-webkit-scrollbar-track-piece {
+ background: var(--color-background);
+ &:vertical {
+ border-left: 1rem solid var(--color-background);
+ }
+ &:horizontal {
+ border-top: 1rem solid var(--color-background);
+ }
+}
+
+::-webkit-scrollbar-thumb {
+ background: var(--color-scrollbar);
+ &:active {
+ background: var(--color-scrollbar-on);
+ }
+ &:vertical {
+ border-left: 1rem solid var(--color-background);
+ }
+ &:horizontal {
+ border-top: 1rem solid var(--color-background);
+ }
+}
+
+::-webkit-scrollbar-button:decrement:start, ::-webkit-scrollbar-button:increment:end {
+ height: 0;
+ width: 0;
+}
+
+::-webkit-scrollbar-corner {
+ height: 0rem;
+ width: 0rem;
+ background: var(--color-background);
+}
+
+
+// Firefox
+
+* {
+ scrollbar-color: var(--color-scrollbar) var(--color-background);
+ scrollbar-width: normal;
+}
diff --git a/src/scss/ui/selectarea.scss b/src/scss/ui/selectarea.scss
new file mode 100644
index 00000000..71f1d913
--- /dev/null
+++ b/src/scss/ui/selectarea.scss
@@ -0,0 +1,46 @@
+.select-area {
+
+ position:fixed;
+ z-index:999999;
+ border: 1rem solid var(--color-accent);
+ pointer-events: none;
+ &:after {
+ content:"";
+ position: absolute;
+ top:0;left:0;
+ right:0;bottom:0;
+ background: var(--color-accent);
+ opacity: 0.2;
+ }
+ &.hidden {
+ display: none;
+ }
+
+}
+
+.widget.editing {
+ z-index: 9999!important;
+}
+.widget.editing:after,
+.tablink.editing:after,
+.modal-container.editing > .popup > .popup-wrapper:after {
+ content:"";
+ z-index: 999!important;
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+
+ border-style: solid;
+
+ -webkit-border-image: linear-gradient(to right, var(--color-accent) 10rem, rgba(0, 0, 0, 0) 10rem, rgba(0, 0, 0, 0) calc(100% - 10rem), var(--color-accent) calc(100% - 10rem)) 1 / 1rem;
+ -webkit-mask-image: linear-gradient(to bottom, white 10rem, rgba(0, 0, 0, 0) 10rem, rgba(0, 0, 0, 0) calc(100% - 10rem), white calc(100% - 10rem));
+
+ border-image: linear-gradient(to right, var(--color-accent) 10rem, rgba(0, 0, 0, 0) 10rem, rgba(0, 0, 0, 0) calc(100% - 10rem), var(--color-accent) calc(100% - 10rem)) 1 / 1rem;
+ mask-image: linear-gradient(to bottom, white 10rem, rgba(0, 0, 0, 0) 10rem, rgba(0, 0, 0, 0) calc(100% - 10rem), white calc(100% - 10rem));
+
+ pointer-events: none;
+ box-shadow: none!important;
+ opacity: 1!important;
+}
diff --git a/src/scss/ui/toolbar.scss b/src/scss/ui/toolbar.scss
new file mode 100644
index 00000000..deb3df59
--- /dev/null
+++ b/src/scss/ui/toolbar.scss
@@ -0,0 +1,43 @@
+osc-toolbar {
+ --size: 34rem;
+ position: fixed;
+ top: 0;
+ left: 0;
+ height:var(--size);
+ width:var(--size);
+ max-width:var(--size);
+ min-width:var(--size);
+ text-align: center;
+ z-index: 99999999;
+ cursor: pointer;
+ &:after {
+ content:"\f0c9";
+ width: 3rem;
+ display: inline-block;
+ overflow: hidden;
+ font-size:13rem;
+ font-family: FontAwesome;
+ line-height: calc(var(--size) + 6rem);
+ }
+
+ &.on {
+ &:after {
+ color: var(--color-widget);
+ }
+ }
+}
+
+osc-toolbar#start {
+
+ left: var(--size);
+ &:after {
+ font-size: 11rem;
+ content: "\f04b";
+ width: auto;
+ margin-top:-1rem;
+ }
+ &.started:after {
+ content: "\f04d";
+ }
+
+}
diff --git a/src/scss/ui/tree.scss b/src/scss/ui/tree.scss
new file mode 100644
index 00000000..29aaca88
--- /dev/null
+++ b/src/scss/ui/tree.scss
@@ -0,0 +1,115 @@
+#osc-tree {
+
+ --alpha-fill: 0.5;
+ --widget-padding: -1rem;
+
+ $padding: 16rem;
+ $line-height: 28rem;
+ padding: 0 $padding;
+
+
+ text-transform: none;
+ line-height: $line-height;
+
+
+ ol {
+
+ list-style: none;
+ position: relative;
+ padding-left: 16rem;
+
+ ol:before {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: $line-height / 2 - 1;
+ left: -12rem;
+ border-left: 1rem solid var(--color-stroke);
+ opacity: 0.25;
+ pointer-events: none;
+ }
+ }
+
+ li {
+
+ position: relative;user-select: none;
+ > ol {
+ display: none;
+ }
+ &.expanded > ol {
+ display: block;
+ }
+
+ li:before {
+ content: "";
+ position: absolute;
+ top: $line-height / 2;
+ left: -27rem;
+ width: 16rem;
+ border-bottom: 1rem solid var(--color-stroke);
+ opacity: 0.25;
+ pointer-events: none;
+ }
+ .container:before {
+ width: 8rem;
+ }
+
+ &.invisible {
+ opacity: 0.5;
+ font-style: italic;
+ // &:after {
+ // content: "\f070";
+ // font-family: FontAwesome;
+ // width: 12rem;
+ // display: block;
+ // position: absolute;
+ // right: -12rem;
+ // }
+ }
+
+ }
+
+ .toggle {
+ &:before {
+ content: "\f054";
+ font-family: FontAwesome;
+ width: 20rem;
+ display: block;
+ position: absolute;
+ left: -21rem;
+ font-style: normal;
+ text-align: center;
+ }
+ cursor: pointer;
+ }
+
+ .container.expanded > .toggle:before {
+ content: "\f078";
+ }
+
+ .editing {
+ z-index: 1;
+ @include pseudo-fill($z: -1);
+ &:after {
+ left: calc(-1 * var(--depth) * 16rem - #{$padding});
+ right: -($padding - 1);
+ bottom: auto;
+ height: $line-height;
+ top: 0;
+ }
+
+ }
+
+ .contains-editing:not(.expanded):not(.editing) {
+ z-index: 1;
+ @include pseudo-fill($z: -1);
+ &:after {
+ left: calc(-1 * var(--depth) * 16rem - #{$padding});
+ right: -($padding - 1);
+ bottom: auto;
+ height: $line-height;
+ opacity: 0.1;
+ }
+ }
+
+}
diff --git a/src/scss/ui/workspaces.scss b/src/scss/ui/workspaces.scss
new file mode 100644
index 00000000..e34b4c7f
--- /dev/null
+++ b/src/scss/ui/workspaces.scss
@@ -0,0 +1,360 @@
+osc-workspace {
+
+ background: var(--color-ui-background);
+
+ --color-fill: var(--color-widget);
+ --color-stroke: var(--color-widget);
+
+ // optimize layout recalc
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+
+ display: flex;
+ flex-direction: row;
+ overflow: hidden;
+
+}
+
+osc-panel-container {
+
+ position: relative;
+ display:flex;
+ flex-direction: column;
+
+
+ &.center {
+ flex: 1;
+ z-index: 1;
+ min-width: 100rem;
+ }
+
+ &.left, &.right {
+ z-index: 2;
+ min-width: 0;
+ width: 0;
+ box-shadow: 0 0 0 1rem var(--color-background);
+
+ &.minimized {
+ box-shadow: none;
+ }
+
+ &:after {
+ // hover trap to display toggle-button when closed
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 1rem;
+ z-index: 1;
+ }
+
+ ::-webkit-scrollbar-thumb, ::-webkit-scrollbar-track-piece {
+ border-color: var(--color-ui-background)!important;
+ }
+
+ }
+ &.left:after {
+ right: -1rem;
+ }
+ &.right:after {
+ left: -1rem;
+ }
+
+ &.bottom, &.top {
+ z-index: 2;
+ min-height: 0;
+ height: 0;
+ &:after {
+ // hover trap to display toggle-button when closed
+ content: "";
+ position: absolute;
+ top: -1rem;
+ height: 1rem;
+ left: 0;
+ right: 0;
+ z-index: 1;
+ }
+ &.top:after {
+ bottom: -1rem;
+ top: auto;
+ }
+ }
+
+ .resize-handle {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 4rem;
+ cursor: ew-resize;
+ z-index: 4;
+ &.right {
+ left: 0;
+ }
+ &.left {
+ right: 0;
+ }
+ &.bottom {
+ top:0;
+ left:0;
+ right:0;
+ height: 4rem;
+ width: auto;
+ cursor: ns-resize;
+ }
+ &.top {
+ top: auto;
+ bottom:0;
+ left:0;
+ right:0;
+ height: 4rem;
+ width: auto;
+ cursor: ns-resize;
+ }
+ }
+
+ .toggle-button {
+
+ position: absolute;
+ top: 50%;
+ height: 50rem;
+ width: 25rem;
+ margin-top: -25rem;
+ cursor: pointer;
+ background: var(--color-ui-background);
+ font-size: 14rem;
+ z-index: 2;
+ transition: transform 0.2s ease-out 0.1s, border-color 0.2s ease-out 0.1s;
+ will-change: transform;
+
+ border-style: solid;
+ border-width: 1rem;
+ border-color: transparent;
+
+ &:after {
+ font-family: FontAwesome;
+ line-height: 50rem;
+ width: 25rem;
+ text-align: center;
+ display: block;
+ opacity: 0;
+ transition: opacity 0.2s ease-out 0s;
+ }
+
+ &.left {
+ border-top-right-radius: 25rem;
+ border-bottom-right-radius: 25rem;
+ right: -25rem;
+ transform: translateX(-25rem);
+ border-left-width: 0;
+ &:after {
+ content:"\f104";
+ margin-left: -4rem;
+ }
+ }
+ &.right {
+ border-top-left-radius: 25rem;
+ border-bottom-left-radius: 25rem;
+ left: -25rem;
+ transform: translateX(25rem);
+ border-right-width: 0;
+
+
+ &:after {
+ content:"\f105";
+ margin-left: 4rem;
+ }
+ }
+
+ &.bottom {
+ border-top-left-radius: 25rem;
+ border-top-right-radius: 25rem;
+ top: -25rem;
+ height: 25rem;
+ width: 50rem;
+ left: 50%;
+ margin-left: -25rem;
+ margin-top: 0;
+ cursor: pointer;
+ transform: translateY(25rem);
+
+ &:after {
+ content:"\f107";
+ margin-top: 2rem;
+ width: 50rem;
+ height: 25rem;
+ line-height: 25rem;
+
+ }
+ }
+
+ &.top {
+ border-bottom-left-radius: 25rem;
+ border-bottom-right-radius: 25rem;
+ top: auto;
+ bottom: -25rem;
+ height: 25rem;
+ width: 50rem;
+ left: 50%;
+ margin-left: -25rem;
+ margin-top: 0;
+ cursor: pointer;
+ transform: translateY(- 25rem);
+
+ &:after {
+ content:"\f106";
+ margin-bottom: 2rem;
+ width: 50rem;
+ height: 25rem;
+ line-height: 25rem;
+
+ }
+ }
+
+ }
+
+ &:hover .toggle-button, .toggle-button:hover {
+ transition: transform 0.2s ease-out 0s, border-color 0.2s ease-out 0s;
+ transform: translateX(0) translateY(0);
+ border-color: var(--color-background);
+ &:after {
+ transition: opacity 0.1s ease-in 0.1s;
+ opacity: 1;
+ }
+ }
+
+ &.minimized .toggle-button {
+ &.left:after {
+ content:"\f105";
+ }
+ &.right:after {
+ content:"\f104";
+ }
+ &.bottom:after {
+ content:"\f106";
+ }
+ &.top:after {
+ content:"\f107";
+ }
+ }
+
+ &.disabled .toggle-button {
+ display: none;
+ }
+
+}
+
+osc-modal-container {
+
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+
+}
+
+osc-panel-inner {
+
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ overflow: hidden;
+ z-index: 3;
+ min-width: 0;
+ position: relative;
+ contain: strict;
+
+}
+
+// @keyframes test{
+// 0% {
+// transform: scaleX(0);
+// opacity: 0;
+// }
+// 100% {
+// tranform: scaleX(1);
+// opacity: var(--alpha-fill);
+// }
+// }
+//
+// osc-panel-container:not(.disabled) osc-panel-header:before {
+// animation: test 0.1s forwards;
+//
+// }
+
+osc-panel-header {
+
+ --alpha-fill: 0.25;
+
+ display: flex;
+ height: var(--nav-height);
+ align-items: center;
+ align-items: center;
+ justify-content: center;
+ position:relative;
+ letter-spacing: 1rem;
+ font-size: 109%;
+ text-overflow: ellipsis;
+ padding: 0 8rem;
+
+ &:before {
+ content: "";
+ position: absolute;
+ left: 0rem;
+ right: 0rem;
+ bottom: 1rem;
+ opacity: var(--alpha-fill);
+ height: 2rem;
+ background: var(--color-fill);
+ z-index: 101;
+ }
+
+}
+
+osc-panel-content {
+
+ flex: 1;
+ overflow-y: auto;
+
+ &.left, &.right {
+ &::-webkit-scrollbar-thumb, &::-webkit-scrollbar-track-piece {
+ border-right: 1rem solid var(--color-ui-background);
+ }
+ }
+
+
+}
+
+
+#osc-greeting-header {
+ --alpha-fill: 0.75;
+ span {
+ opacity: 0.5;
+ position: absolute;
+ right: 12rem;
+ }
+ &.hidden {
+ display: none;
+ + #osc-container {
+ // optimize layout recalc
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ background: rgba(black, 0.5);
+ }
+ }
+
+ border-bottom:1rem solid var(--color-background);
+ &:before {
+ bottom: 0;
+ }
+}
+
+#osc-container {
+ background: var(--color-background);
+ overflow: auto;
+}
diff --git a/src/scss/widgets.scss b/src/scss/widgets.scss
new file mode 100644
index 00000000..25a41eaa
--- /dev/null
+++ b/src/scss/widgets.scss
@@ -0,0 +1,82 @@
+.widget {
+
+ overflow: hidden;
+ position:relative;
+ vertical-align:top;
+
+ display: inline-flex;
+ flex-direction: row;
+ align-items: stretch;
+
+ max-width: 100%;
+ max-height: 100%;
+ width: 100rem;
+ height: 100rem;
+
+
+ contain: strict;
+ @supports not (contain: strict) {
+ transform: rotateZ(0); // force new stacking context
+ }
+
+ -webkit-tap-highlight-color:transparent;
+
+ // transform-origin: top left;
+
+ --line-width: 1rem;
+ --widget-padding: 1rem;
+
+ --color-stroke:var(--color-widget);
+ --color-fill:var(--color-widget);
+
+ --alpha-stroke: 0.5;
+ --alpha-fill-off: 0.0;
+ --alpha-fill-on: 0.25;
+ --alpha-fill: var(--alpha-fill-off);
+
+ --alpha-pips: 0.5;
+ --alpha-pips-text: 0.7;
+
+
+ color: var(--color-text);
+
+ background-color: var(--color-background);
+ background-clip: content-box;
+
+
+ &.absolute-position {
+ position: absolute;
+ z-index: 10;
+ }
+
+ canvas {
+ flex: 1;
+ height: auto;
+ min-height: 0;
+ min-width: 0;
+ }
+
+ > inner {
+ overflow: hidden;
+ position: relative;
+ flex: 1;
+ border-radius: inherit;
+ }
+
+ &.no-interaction {
+ pointer-events: none;
+ > * {
+ pointer-events: none
+ }
+ }
+
+}
+
+
+@import 'widgets/basics';
+@import 'widgets/containers';
+@import 'widgets/graphs';
+@import 'widgets/frames';
+@import 'widgets/indicators';
+@import 'widgets/pads';
+@import 'widgets/sliders';
diff --git a/src/scss/widgets/basics.scss b/src/scss/widgets/basics.scss
new file mode 100644
index 00000000..a6546ca4
--- /dev/null
+++ b/src/scss/widgets/basics.scss
@@ -0,0 +1,625 @@
+.button-container {
+ width: 90rem;
+ height: 60rem;
+}
+.menu-container,
+.dropdown-container,
+.input-container,
+.file-container {
+ width: 90rem;
+ height: 30rem;
+}
+
+
+@keyframes osc-button-pulse {
+ 0% {opacity: var(--alpha-fill-on);}
+ 100% {opacity: var(--alpha-fill-off);}
+}
+
+.button-container {
+
+ --alpha-fill-off: .15;
+ --alpha-fill-on: .75;
+ --widget-padding: -1rem;
+ --color-text-on: var(--color-background);
+
+ inner {
+
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ margin: var(--widget-spacing);
+ padding: var(--widget-padding);
+
+
+ @include pseudo-stroke($z: -1);
+ @include pseudo-fill($z: -1);
+
+ }
+
+ label {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ white-space: pre;
+ overflow: hidden;
+ text-align: center;
+ word-wrap: break-word;
+ height: 100%;
+ width: 100%;
+ border: 2rem solid transparent;
+
+ &.wrap {
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ &.vertical {
+ transform: rotate(180deg);
+ text-overflow: ellipsis;
+ -webkit-writing-mode:vertical-rl;
+ writing-mode:vertical-rl;
+ i {
+ transform: rotate(180deg);
+ writing-mode: initial;
+ }
+ }
+ }
+
+ &.on {
+
+ --alpha-fill:var(--alpha-fill-on);
+ color: var(--color-text-on);
+
+ }
+
+ // &.active {
+ //
+ // color: var(--color-text-on);
+ //
+ // }
+
+ &.pulse inner:after {
+ animation: osc-button-pulse .15s 1 forwards;
+ }
+
+}
+
+.switch-container {
+
+ --alpha-fill-off: .15;
+ --alpha-fill-on: 0.75;
+ --alpha-fill: var(--alpha-fill-off);
+ --color-text-on: var(--color-background);
+
+ @include pseudo-stroke();
+ &:before {
+ margin: var(--widget-spacing);
+ }
+
+ inner {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ --widget-spacing: calc(var(--widget-padding) / 2);
+ margin: calc(var(--widget-spacing) + var(--line-width));
+
+
+ }
+
+ &.padding-0 inner {
+ // style fix for padding == -1
+ margin: 0;
+
+ }
+
+ &.layout-horizontal inner {
+
+ flex-direction: row;
+
+ }
+
+ &.layout-grid inner {
+
+ display:grid;
+
+ }
+
+
+ value {
+
+ position: relative;
+ z-index: 1;
+ padding: 4rem;
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ text-overflow: clip;
+ overflow: hidden;
+ @include pseudo-fill($z: -1);
+ &:after {
+ --line-width: 1rem;
+ margin: calc(var(--widget-spacing) - 1rem);
+ }
+
+ &.on {
+ --alpha-fill: var(--alpha-fill-on);
+
+ color: var(--color-text-on);
+ }
+
+ }
+
+}
+
+// @keyframes menu-widget-fade {
+// 0% {
+// transform: scale(0)
+// }
+// 100% {
+// transform: scale(1)
+// }
+// }
+
+.menu-container {
+
+ --alpha-fill-off: .15;
+ --alpha-fill-on: .75;
+ --alpha-fill-hover: calc(var(--alpha-fill-on) / 2);
+ --widget-padding: 1rem;
+ --text-padding: calc(var(--widget-padding) + 8rem);
+
+ z-index: initial!important;
+ // contain: style size;
+
+ --size: 300rem;
+ --grid-columns: 2;
+
+ --parent-scroll-x: 0;
+ --parent-scroll-y: 0;
+
+ overflow: hidden;
+
+
+ &.on {
+ z-index: 9999999999999!important;
+ contain: size;
+ overflow: visible;
+ }
+
+
+ inner {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: center;
+ position: relative;
+ @include pseudo-stroke();
+ @include pseudo-fill($z: -1);
+
+ &.text-align-right .text {
+ justify-content: flex-end;
+ }
+ &.text-align-left .text{
+ justify-content: flex-start;
+ }
+
+
+ &.menu-align-h-right {
+ justify-content: flex-end;
+ }
+ &.menu-align-h-left{
+ justify-content: flex-start;
+ }
+ &.menu-align-v-top {
+ align-items: flex-start;
+ }
+ &.menu-align-v-bottom{
+ align-items: flex-end;
+ }
+
+ }
+
+ .text {
+ flex: 1;
+ height: 100%;
+ text-align: center;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding-left: var(--text-padding);
+ }
+ .icon {
+ order: 1;
+ display: block;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 30rem;
+ height: calc(100% - 2rem);
+ font-family: FontAwesome;
+ font-size: 120%;
+ margin: 1rem 0;
+ margin-right: var(--widget-padding);
+ z-index: 1;
+ &:after {
+ content:"\f107";
+ }
+ }
+
+
+ menu {
+
+ // animation: menu-widget-fade .1s forwards;
+ position: fixed;
+ z-index: 999999999;
+
+ margin-left: calc(-1 * var(--parent-scroll-x));
+ margin-top: calc(-1 * var(--parent-scroll-y));
+
+ overflow: hidden;
+
+ background: var(--color-background);
+
+ @include pseudo-stroke($z: 2);
+ &:before {
+ border-width: var(--line-width);
+ }
+
+
+ .item {
+
+ z-index: 1;
+ overflow: hidden;
+ div {
+ text-align: center;
+ pointer-events: none;
+ }
+
+ }
+
+ }
+
+ &.circular menu {
+
+ border-radius: 100%;
+ width:var(--size);
+ height:var(--size);
+
+
+ &:after {
+ content:"";
+ position: absolute;
+ width: calc(var(--size) / 4 - 12rem);
+ height: calc(var(--size) / 4 - 12rem);
+ top:50%;
+ left: 50%;
+ margin-left: calc(-1 * var(--size) / 8 + 6rem);
+ margin-top: calc(-1 * var(--size) / 8 + 6rem);
+ background: var(--color-background);
+ box-shadow: 0 0 0 2rem var(--color-background), 0 0 0 3rem var(--color-stroke);
+ border-radius: 100%;
+ z-index: 10;
+ opacity: var(--alpha-stroke);
+ }
+
+ .item {
+ top: calc(-1 * var(--size) / 2);
+ left: calc(-1 * var(--size) / 2);
+ width: 100%;
+ height: 100%;
+ transform-origin: 100% 100%;
+ position: absolute;
+ box-shadow: 0 0 0 2rem var(--color-background);
+
+
+ div {
+ position: absolute;
+ bottom: 0;
+ right: 0;
+ &:before {
+ content:"";
+ position: absolute;
+ width: calc(var(--size) / 4);
+ height: calc(var(--size) / 4);
+ left: calc(-1 * var(--size) / 8);
+ top: calc(-1 * var(--size) / 8);
+ border-radius: 100%;
+ pointer-events: none;
+ box-shadow: 0 0 0 4rem var(--color-fill);
+ opacity: 0;
+ }
+ }
+
+ &.on {
+ color: var(--color-fill);
+ }
+
+ &.on div:before {
+ opacity: var(--alpha-fill-on)!important;
+ }
+ &.active div:before, &:hover div:before {
+ opacity: var(--alpha-fill-hover);
+ }
+
+
+ span {
+ position: absolute;
+ top: calc(-1 * var(--size) / 3);
+ width: calc(var(--size) / 2);
+ margin-left: calc(-1 * var(--size) / 4);
+ }
+
+ }
+
+
+ }
+
+ &.box menu {
+
+ width:var(--size-box-w);
+ height:var(--size-box-h);
+
+ display: flex;
+
+ flex-direction: row;
+ padding: calc(var(--widget-padding) / 2 + var(--line-width));
+
+ .item {
+ position: relative;
+ margin: calc(var(--widget-padding) / 2);
+
+
+ div {
+ @include pseudo-fill($z: -1);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100%;
+ flex: 1;
+ &:after {
+ opacity: 0;
+ margin: 0;
+ top:0;left:0;right:0;bottom:0;
+ }
+ }
+
+ &.on {
+ color: var(--color-background);
+ div:after {
+ opacity: var(--alpha-fill-on)!important;
+ }
+ }
+
+ &.active, &:hover {
+ div:after, div:after {
+ opacity: var(--alpha-fill-hover);
+ }
+ }
+
+
+ }
+
+ }
+
+ &.grid.on menu {
+
+ display: grid;
+ grid-template-columns: repeat(var(--grid-columns), 1fr);
+
+ }
+
+ &.vertical menu {
+
+ flex-direction: column;
+
+ }
+
+}
+
+
+.dropdown-container {
+
+ --alpha-fill-off: .15;
+ --alpha-fill-on: .75;
+ --widget-padding: 1rem;
+ --text-padding: calc(var(--widget-padding) + 8rem);
+
+ z-index: initial!important;
+ // contain: style size;
+
+ --size: 300rem;
+ --grid-columns: 2;
+ overflow: hidden;
+
+
+ &.on {
+ z-index: 9999999999999!important;
+ contain: layout;
+ overflow: visible;
+ }
+
+
+ inner {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: stretch;
+ position: relative;
+ @include pseudo-stroke();
+ @include pseudo-fill($z: -1);
+
+ &.right .text {
+ justify-content: flex-end;
+ }
+ &.left .text{
+ justify-content: flex-start;
+ }
+ }
+
+ .text {
+ flex: 1;
+ text-align: center;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding-left: var(--text-padding);
+ }
+ .icon {
+ order: 1;
+ display: block;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 30rem;
+ font-family: FontAwesome;
+ font-size: 120%;
+ margin-right: var(--widget-padding);
+ &:after {
+ content:"\f107";
+ }
+ }
+
+ select {
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ width: 100%;
+ -webkit-appearance:none;
+ -moz-appearance:none;
+ appearance:none;
+ background: var(--color-background);
+ opacity: 0;
+ }
+
+}
+
+
+
+.input-container {
+
+ --alpha-fill-off: 0.05;
+ --text-padding: calc(var(--widget-padding) + 8rem);
+
+ inner {
+ position: relative;
+ @include pseudo-stroke();
+ @include pseudo-fill(0.05);
+ justify-content: center;
+ align-items: center;
+ display: flex;
+ padding: var(--widget-padding);
+ text-align: center;
+ &.right {
+ text-align: right;
+ }
+ &.left {
+ text-align: left;
+ }
+
+ padding: 0 var(--text-padding);
+
+ }
+
+ input + canvas {
+ display: none;
+ width: 0;
+ }
+
+ canvas {
+ flex:1;
+ max-width: 100%;
+ }
+
+ input {
+ display: block;
+ flex:1;
+ max-width: 100%;
+ font: inherit;
+ border:0;
+ padding:0;
+ background: transparent;
+ border-radius: inherit;
+ -webkit-appearance:none;
+ appearance: none;
+ text-align:inherit;
+ vertical-align: top;
+ letter-spacing: 1rem;
+ -webkit-user-select: text;
+ user-select: text;
+
+ color:var(--color-fill);
+ caret-color: var(--color-fill);
+
+
+
+ &:focus::selection {
+ background: var(--color-fill);
+ color: var(--color-text);
+ }
+
+ }
+
+}
+
+.editor-enabled .input-container:not(.editing) inner {
+ // prevent input focus when selecting
+ pointer-events: none;
+}
+
+
+.file-container {
+
+ --alpha-fill-off: .15;
+ --alpha-fill-on: .75;
+ --widget-padding: 1rem;
+ --text-padding: calc(var(--widget-padding) + 8rem);
+
+ inner {
+ flex:1;
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: stretch;
+ position: relative;
+ @include pseudo-stroke();
+ @include pseudo-fill($z: -1);
+
+ &.right .text {
+ justify-content: flex-end;
+ }
+ &.left .text{
+ justify-content: flex-start;
+ }
+ }
+
+ .text {
+ flex: 1;
+ text-align: center;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding-left: var(--text-padding);
+ min-width: 0;
+ overflow: hidden;
+ }
+ .icon {
+ order: 1;
+ display: block;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 30rem;
+ font-family: FontAwesome;
+ font-size: 120%;
+ margin-right: var(--widget-padding);
+ &:after {
+ content:"\f07c";
+ }
+ }
+
+}
diff --git a/src/scss/widgets/containers.scss b/src/scss/widgets/containers.scss
new file mode 100644
index 00000000..dd5ebbb3
--- /dev/null
+++ b/src/scss/widgets/containers.scss
@@ -0,0 +1,668 @@
+.panel-container {
+ width: 200rem;
+ height: 200rem;
+}
+.modal-container {
+ width: 90rem;
+ height: 60rem;
+}
+.keyboard-container {
+ width: 220rem;
+ height: 90rem;
+}
+.patchbay-container {
+ width: 240rem;
+ height: 160rem;
+}
+
+
+.widget-panel-base {
+
+ --widget-padding: 4rem;
+
+ background-color: var(--color-background);
+
+
+ > inner {
+ overflow: auto;
+ }
+
+
+
+ &.no-scroll > inner {
+ overflow: hidden;
+ }
+
+ &.contains-widgets {
+
+ > inner {
+ --widget-spacing: calc(var(--widget-padding) / 2);
+ margin: var(--widget-spacing);
+ }
+
+ &.no-inner-padding > inner {
+ margin: calc(var(--widget-spacing) * -1);
+ }
+
+ > inner > .widget {
+ padding: var(--widget-spacing);
+ }
+
+ &.layout-default > inner {
+ display: block;
+ }
+ &.layout-horizontal > inner {
+ display: flex;
+ flex-direction: row;
+ align-items: stretch;
+ > .widget {
+ top:auto!important;
+ left:auto!important;
+ position: relative!important;
+ height: auto!important;
+ min-height: auto!important;
+ max-height: 100%;
+ }
+ > .flex-expand {
+ flex: 1
+ }
+ }
+
+ &.layout-horizontal.layout-contain > inner > .widget {
+ min-width: auto!important;
+ max-width: 100%;
+ }
+
+ &.layout-vertical > inner {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ > .widget {
+ top:auto!important;
+ left:auto!important;
+ position: relative!important;
+ width: auto!important;
+ min-width: auto!important;
+ max-width: 100%;
+ }
+ > .flex-expand {
+ flex: 1
+ }
+ }
+ &.layout-vertical.layout-contain > inner > .widget {
+ min-height: auto!important;
+ max-height: 100%;
+ }
+
+ &.layout-grid > inner {
+ display: grid;
+ > .widget {
+ top:auto!important;
+ left:auto!important;
+ position: relative!important;
+ height: auto!important;
+ width: auto!important;
+ min-height: auto!important;
+ max-height: auto!important;
+ min-width: auto!important;
+ max-width: auto!important;
+ }
+ }
+
+ }
+
+
+ &.contains-tabs {
+
+ > inner {
+
+ --widget-spacing: 0;
+
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+
+ > .widget {
+ flex: 1;
+ width: 100%;
+ height: auto;
+ padding: 0;
+ }
+ }
+
+ &.vertical-tabs {
+
+ > inner {
+ flex-direction: row;
+ }
+
+ }
+ }
+
+}
+
+.tab-container {
+ @extend .widget-panel-base;
+
+ // --widget-padding: 0rem;
+ --alpha-fill-on: 0.75;
+
+ width: 100%;
+ height: 100%;
+ background-color: var(--color-background);
+
+ &:not(.show) {
+ display:none
+ }
+
+}
+.tab-container.editing {
+ z-index: initial!important;
+ &:after {
+ display:none;
+ }
+}
+.tablink.editing:after {
+ margin: 2rem 2rem 4rem;
+}
+
+
+.panel-container {
+
+ @extend .widget-panel-base;
+
+ --alpha-fill-on: 0.75;
+
+ @include pseudo-stroke($z: 1);
+ &:before {
+ margin: var(--widget-spacing);
+ }
+
+ &.contains-tabs {
+ > inner {
+ margin: calc(var(--line-width));
+ }
+ }
+
+ &.contains-widgets {
+
+ > inner {
+ margin: calc(var(--widget-spacing) + var(--line-width));
+ }
+
+ &.no-inner-padding > inner {
+ margin: calc(var(--widget-spacing) * -1);
+ }
+ }
+
+
+}
+
+.root-container {
+
+ @extend .widget-panel-base;
+
+ --alpha-fill-on: 0.75;
+
+ width: 100%;
+ height: 100%;
+
+ // optimize layout recalc
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+
+ > inner {
+ margin: var(--widget-spacing);
+
+ // optimize layout recalc
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ }
+
+ margin: auto;
+
+}
+
+.root-container.editing {
+ &:after {
+ display:none;
+ }
+}
+
+
+
+.navigation {
+
+ background-color: var(--color-ui-background);
+
+ height:calc(var(--nav-height) - 1rem);
+ flex-shrink:0;
+ display: flex;
+ // padding-bottom: 1rem;
+ position: relative;
+
+ &:before {
+ content:"";
+ position: absolute;
+ // border-bottom: 1rem solid var(--color-stroke);
+ opacity: var(--alpha-stroke);
+ left: 0;
+ right: 0;
+ bottom: 0;
+ }
+
+ div {
+
+ // --color-stroke:var(--color-widget);
+ --color-fill:var(--color-widget);
+
+ color: var(--color-text);
+
+ line-height:calc(var(--nav-height) - 1rem);
+ display:flex;
+ min-width:0;
+ flex: 1 1 100%;
+ cursor:pointer;
+ height:100%;
+ align-items: center;
+ align-items: center;
+ justify-content: center;
+ position:relative;
+ letter-spacing: 1rem;
+ font-size: 109%;
+ text-overflow: ellipsis;
+ padding: 0 8rem;
+ overflow: hidden!important;
+ white-space: pre-wrap;
+ text-align: center;
+
+ i {
+ pointer-events: none;
+ position: relative;
+ }
+
+ &.on {
+ z-index: 1;overflow: visible;
+ &:before {
+ content: "";
+ position: absolute;
+ left: 0rem;
+ right: 0rem;
+ bottom: 0rem;
+ opacity: var(--alpha-fill-on);
+ height: 2rem;
+ background: var(--color-fill);
+ z-index: 101;
+ }
+ &:first-child:before {
+ margin-left: 1rem;
+ }
+ &:last-child:before {
+ margin-right: 1rem;
+ }
+
+ }
+ }
+
+ &.vertical {
+ flex-direction: column;
+ height: 100%;
+ padding-bottom: 0;
+ // padding-right: 1rem;
+
+ div {
+ height: 100%;
+ padding: 0 12rem;
+ line-height: normal;
+ // justify-content: flex-start;
+ // text-align: left;
+
+ &.on:before {
+ content: "";
+ position: absolute;
+ left: auto;
+ top: 0rem;
+ right: 0rem;
+ bottom: 0rem;
+ opacity: var(--alpha-fill-on);
+ width: 2rem;
+ height: auto;
+ background: var(--color-fill);
+ z-index: 101;
+ }
+ &:first-child:before {
+ margin-top: 1rem;
+ margin-left: 0;
+ }
+ &:last-child:before {
+ margin-bottom: 1rem;
+ margin-right: 0;
+ }
+ }
+ }
+}
+
+
+.clone-container {
+
+ &.empty {
+ @include pseudo-stroke();
+ &:before {
+ margin: var(--widget-spacing);
+ }
+ }
+
+ &:before {
+ content: none
+ }
+
+ > .clone {
+
+ --widget-spacing: 0;
+ flex: 1;
+
+ > .widget {
+ border:0!important;
+ box-shadow: none!important;
+ position: relative!important;
+ left:auto!important;
+ bottom:auto!important;
+ right:auto!important;
+ top: auto!important;
+ width: 100%!important;
+ height: 100%!important;
+ min-height: initial!important;
+ max-height: initial!important;
+ min-width: initial!important;
+ max-width: initial!important;
+ padding: 0!important;
+ }
+ }
+}
+
+
+
+.modal-container {
+
+ --widget-padding: 4rem;
+ --color-text-on: var(--color-background);
+ --alpha-fill-off: 0.15;
+ --alpha-fill-on: .75;
+
+ > .toggle {
+
+ --widget-padding: -1rem;
+
+ position: absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ margin: var(--widget-spacing);
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ border-radius: inherit;
+
+ @include pseudo-stroke();
+ @include pseudo-fill($z: -1);
+
+ }
+
+ > label {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ white-space: pre;
+ overflow: hidden;
+ text-align: center;
+ word-wrap: break-word;
+ height: 100%;
+ width: 100%;
+ border: 2rem solid transparent;
+ }
+
+ &.on {
+
+ > .toggle {
+ --alpha-fill:var(--alpha-fill-on);
+ }
+ > label {
+ color: var(--color-text-on);
+ }
+
+ z-index: 9999999999999!important;
+ overflow: visible;
+
+ contain: size;
+ @supports not (contain: strict) {
+ transform: none; // cancel new stacking context
+ z-index: initial!important; // iOS does it wrong otherwise
+
+ }
+
+ }
+
+
+
+
+
+
+ > inner {
+ display: none;
+ }
+
+ &.no-inner-padding > .popup > .popup-wrapper > .popup-content > inner {
+ margin: calc(var(--widget-spacing) * -1);
+ }
+ &.modal-breakout > .popup > .popup-wrapper > .popup-content {
+ @extend .modal-breakout;
+ }
+
+
+ > .popup {
+ padding:0;
+
+ > .popup-wrapper {
+ width: var(--width, 100%);
+ height: var(--height, 100%);
+
+ > .popup-content {
+ // contain:unset; // == no restrain
+ padding: 0;
+ &:before {
+ content: none;
+ }
+
+ > inner {
+ margin: var(--widget-spacing);
+ }
+ }
+ }
+
+ &.no-label > .popup-wrapper > .popup-title {
+ display: none;
+ }
+
+ &.x-positionned {
+ justify-content: flex-start;
+ > .popup-wrapper {
+ left: var(--left);
+ }
+ }
+ &.y-positionned {
+ align-items:flex-start;
+ > .popup-wrapper {
+ top: var(--top);
+ }
+ }
+
+ }
+
+}
+
+.modal-breakout {
+ z-index: initial!important;
+ contain: size!important;
+ @supports not (contain: strict) {
+ transform: none!important; // cancel new stacking context
+ }
+}
+
+
+
+.matrix-container {
+
+ @extend .panel-container;
+
+
+ &.layout-vertical, &.layout-horizontal {
+ > inner > .widget {
+ flex: 1;
+ }
+ }
+
+}
+
+
+.patchbaynode-container {
+
+ justify-content: center;
+ background: transparent;
+
+}
+.patchbay-container {
+
+ --alpha-fill-on: .75;
+ --alpha-fill-off: 0.25;
+
+ inner {
+ display: flex;
+ flex-direction: row;
+
+ @include pseudo-stroke();
+ padding: var(--widget-padding);
+
+ canvas {
+ flex: 1;
+ width: 0;
+ }
+ .nodes {
+ display: flex;
+ flex-direction: column;
+ align-items:stretch;
+ margin-bottom: var(--line-width);
+ width: 25%;
+ }
+
+ .inputs, .outputs {
+ position: relative;
+ @include pseudo-stroke();
+ top: var(--line-width);
+ margin-top: -1rem;
+ height: calc(100% - var(--line-width) * 2 + 2rem);
+ }
+
+ .inputs:before {
+ border-width: 0 var(--line-width) 0 0;
+ }
+ .outputs:before {
+ border-width: 0 0 0 var(--line-width);
+ }
+ }
+
+ label {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ white-space: pre;
+ line-height: 100%;
+ overflow: hidden;
+ text-align: center;
+ word-wrap: break-word;
+ height: 100%;
+ width: 100%;
+ border: 2rem solid transparent;
+ pointer-events: none;
+ }
+
+}
+
+
+.keyboard-container {
+
+ --widget-padding: 0rem;
+ --alpha-fill-off: 0;
+ --alpha-fill-on: .75;
+
+ --color-key-on: var(--color-fill);
+ --alpha-key-off: var(--alpha-fill-off);
+ --alpha-key-on: var(--alpha-fill-on);
+ --color-white-key: #ccc;
+ --color-black-key: #1A1A1A;
+
+ --widget-keypad: calc(var(--widget-padding) + var(--line-width));
+
+ > inner {
+
+ padding: calc(var(--widget-padding) + var(--line-width));
+ flex: 1;
+ @include pseudo-stroke($z: 2);
+ position: relative;
+ display: flex;
+ flex-direction: row;
+ overflow: hidden;
+ }
+
+ .key {
+
+ --alpha-fill-off: var(--alpha-key-off);
+ --alpha-fill-on: var(--alpha-key-on);
+ --line-width: 0!important;
+ inner {
+ margin: 1rem 0.5rem!important;
+ --widget-padding: -1rem;
+ &:before {
+ content: none;
+ }
+ &:after {
+ background: var(--color-key-on);
+ z-index: 1;
+ }
+ }
+ }
+
+ .white {
+ flex: 1;
+ width: auto;
+ min-width: auto;
+ height: auto;
+ inner {
+ background: var(--color-white-key);
+ }
+ }
+
+ .black {
+ position: absolute;
+ z-index: 1;
+
+ left: calc((100% - var(--widget-keypad) * 2) / var(--nkeys) * var(--rank));
+ width: calc(100% / var(--nkeys) * 0.6);
+ margin-left: calc(100% / var(--nkeys) * -0.3 + var(--widget-keypad));
+ height: calc((100% - var(--widget-keypad) * 2) * 0.65);
+
+ inner {
+ margin-left: 0!important;
+ margin-right: 0!important;
+ margin-bottom: 0!important;
+ background: var(--color-black-key);
+ }
+ }
+
+}
diff --git a/src/scss/widgets/frames.scss b/src/scss/widgets/frames.scss
new file mode 100644
index 00000000..781e6d5c
--- /dev/null
+++ b/src/scss/widgets/frames.scss
@@ -0,0 +1,34 @@
+.image-container,
+.html-container,
+.svg-container,
+.frame-container {
+
+ width: 120rem;
+ height: 120rem;
+
+ inner {
+ position: relative;
+ flex: 1;
+ display: flex;
+ padding: calc(var(--widget-spacing) + var(--line-width));
+ background-clip: content-box;
+ @include pseudo-stroke();
+ }
+
+ .frame {
+ position: relative;
+ width: 100%;
+ flex: 1;
+ }
+
+}
+
+.frame-container {
+ iframe[src=""] {
+ pointer-events: none;
+ }
+}
+
+.editor-enabled .frame-container iframe {
+ pointer-events: none;
+}
diff --git a/src/scss/widgets/graphs.scss b/src/scss/widgets/graphs.scss
new file mode 100644
index 00000000..016b2c4f
--- /dev/null
+++ b/src/scss/widgets/graphs.scss
@@ -0,0 +1,27 @@
+.eq-container,
+.visualizer-container,
+.plot-container {
+
+ width: 200rem;
+ height: 200rem;
+
+ --alpha-fill-off: 0.05;
+ --alpha-fill-on: 0.1;
+ --widget-padding: 20rem;
+
+ inner {
+ position: relative;
+ flex: 1;
+ display: flex;
+
+ @include pseudo-fill($z: -1);
+ @include pseudo-stroke();
+ // padding: var(--widget-padding);
+ }
+
+ canvas {
+ // margin: var(--widget-padding);
+ width: 100%;
+ }
+
+}
diff --git a/src/scss/widgets/indicators.scss b/src/scss/widgets/indicators.scss
new file mode 100644
index 00000000..4a931382
--- /dev/null
+++ b/src/scss/widgets/indicators.scss
@@ -0,0 +1,96 @@
+.led-container {
+
+ width: 30rem;
+ height: 30rem;
+
+ --color-led: var(--color-fill);
+ --alpha-fill-off: 0;
+ --alpha-fill-on: 1;
+
+ will-change: --opacity;
+
+ inner {
+
+
+ --color-fill: var(--color-led);
+ --alpha-fill: calc(var(--alpha-fill-off) + var(--opacity) * (var(--alpha-fill-on) - var(--alpha-fill-off)));
+
+ position: relative;
+ flex: 1;
+ padding: --widget-padding;
+
+ @include pseudo-stroke();
+ @include pseudo-fill();
+
+ &:before, &:after {
+ border-radius: var(--border-radius);
+ will-change: opacity;
+ }
+ }
+
+}
+
+.text-container {
+
+ width: 90rem;
+ height: 60rem;
+
+ --alpha-stroke: 0;
+ --alpha-fill-off: 0.1;
+ --alpha-fill-on: 1;
+ --widget-padding: -1rem;
+ --text-padding: calc(var(--widget-padding) + 8rem);
+
+ inner {
+ @include pseudo-stroke();
+ @include pseudo-fill($z: -1);
+
+ padding: var(--widget-padding);
+
+ display: flex;
+ width: 100%;
+
+ }
+
+ label {
+
+ opacity: var(--alpha-fill-on);
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ white-space: pre;
+ line-height: 100%;
+ overflow: hidden;
+ text-align: center;
+ word-wrap: break-word;
+ padding: 0 var(--text-padding);
+
+ &.right {
+ text-align: right;
+ justify-content: flex-end;
+ }
+ &.left {
+ text-align: left;
+ justify-content: flex-start;
+ }
+ &.wrap {
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ &.vertical {
+ transform: rotate(180deg);
+ text-overflow: ellipsis;
+ -webkit-writing-mode:vertical-rl;
+ writing-mode:vertical-rl;
+ i {
+ transform: rotate(180deg);
+ writing-mode: initial;
+ }
+ }
+ i {
+ margin-top: -1rem;
+ }
+ }
+}
diff --git a/src/scss/widgets/pads.scss b/src/scss/widgets/pads.scss
new file mode 100644
index 00000000..89f7cbab
--- /dev/null
+++ b/src/scss/widgets/pads.scss
@@ -0,0 +1,127 @@
+.xy-container,
+.multixy-container,
+.rgb-container {
+ width: 200rem;
+ height: 200rem;
+}
+
+.xy-container, .multixy-container {
+
+ --alpha-fill-off: 0.05;
+ --alpha-fill: var(--alpha-fill-off);
+ --widget-padding: 20rem;
+
+ inner {
+ position: relative;
+ flex: 1;
+ display: flex;
+
+ @include pseudo-fill($z: -1);
+ @include pseudo-stroke();
+ }
+
+ canvas {
+ width: 100%;
+ text-align: center;
+ }
+
+}
+
+.multixy-container {
+
+ canvas:not(:first-child) {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ width: 100%;
+ pointer-events: none;
+ }
+
+}
+
+.rgb-container {
+
+ --widget-padding: 4rem;
+
+ > inner {
+
+ display: grid;
+
+ @include pseudo-stroke($z: 1);
+
+ --widget-spacing: calc(var(--widget-padding) / 2);
+
+ padding: calc(var(--line-width) + var(--widget-spacing));
+
+ grid-template:
+ "a a b" auto / 1fr;
+
+ }
+
+ &.contains-alpha > inner {
+ grid-template:
+ "a a b" auto
+ "c c c" calc(20rem + var(--widget-spacing) * 2) / 1fr;
+ }
+
+ .widget {
+ height: auto;
+ width: auto;
+ margin: var(--widget-spacing);
+ --widget-padding: 2rem;
+ --line-width: 0;
+ }
+
+ .pad {
+ grid-area: a;
+
+ background-color: red;
+ background-image: linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,1) 100%), linear-gradient(to right, rgba(255,255,255,1) 0%, rgba(255,255,255,0) 100%);
+ --color-fill: black;
+ --color-stroke: white;
+ --alpha-fill-off: 1;
+ --alpha-fill-on: 1;
+ --alpha-stroke: 1;
+ inner {
+ &:after, &:before {
+ content: none;
+ }
+ }
+ }
+
+ .hue {
+ grid-area: b;
+ width: 20rem;
+
+ --color-fill: white;
+ // --color-stroke: white;
+ --alpha-fill-off: 0.5;
+ --alpha-fill-on: 0;
+ --alpha-stroke: 0;
+ --widget-padding: 0rem;
+
+ &:after {
+ content:"";
+ position: absolute;
+ top: 0;
+ left: 2rem;
+ right: 2rem;
+ bottom: 0;
+ background: linear-gradient(to bottom, #F00, #FF0080, #F0F, #8000FF, #00F, #0080FF, #0FF, #00FF80, #0F0, #80FF00, #FF0, #FF8000, #F00) repeat scroll 0% 0%;
+ opacity: 0.75;
+ z-index: -1;
+ }
+ }
+
+ .alpha {
+ grid-area: c;
+ height: auto!important;
+ width: auto!important;
+ --alpha-stroke: 0;
+ --alpha-fill-off: 0.1;
+ --alpha-fill-on: 0.25;
+ --widget-padding: 0rem;
+ }
+
+}
diff --git a/src/scss/widgets/sliders.scss b/src/scss/widgets/sliders.scss
new file mode 100644
index 00000000..04952919
--- /dev/null
+++ b/src/scss/widgets/sliders.scss
@@ -0,0 +1,67 @@
+.fader-container,
+.knob-container,
+.encoder-container,
+.range-container {
+ canvas {
+ image-rendering: pixelated;
+ width: 100%;
+ height: auto;
+ }
+
+}
+
+.fader-container,
+.range-container {
+
+ width: 50rem;
+ height: 200rem;
+
+ --widget-padding: 1rem;
+ --knob-size: 1rem;
+ --line-width: 1rem;
+
+ canvas {
+ text-align: left;
+ }
+
+ &.horizontal {
+ width: 200rem;
+ height: 50rem;
+ }
+
+ &.design-default {
+ --knob-size: 20rem;
+ --widget-padding: 10rem;
+ --alpha-stroke: 0.5;
+ --alpha-fill-off: 0.25;
+ --alpha-fill-on: 1;
+ --line-width: 2rem
+ }
+
+ &.design-round {
+ --knob-size: 20rem;
+ --widget-padding: 10rem;
+ --alpha-stroke: 0.25;
+ --alpha-fill-off: 0.25;
+ --alpha-fill-on: 1;
+ --line-width: 2rem
+ }
+
+}
+
+.knob-container,
+.encoder-container {
+
+ width: 100rem;
+ height: 100rem;
+
+ --widget-padding: 1rem;
+ --alpha-stroke: 0.75;
+
+ &.design-solid, &.design-line {
+ --alpha-fill-off: 0.25;
+ --alpha-fill-on: 1;
+ --line-width: 2rem;
+ }
+
+}
diff --git a/src/server/address.js b/src/server/address.js
new file mode 100644
index 00000000..b7969f38
--- /dev/null
+++ b/src/server/address.js
@@ -0,0 +1,9 @@
+var ifaces = require('os').networkInterfaces(),
+ address = Object.values(ifaces)
+ .reduce((a,b)=>a.concat(b), [])
+ .filter(i=>i.family === 'IPv4')
+ .map(i=>i.address + ':')
+
+module.exports = (proto, port)=>{
+ return address.map(x=>proto + x + port)
+}
diff --git a/src/server/auth.js b/src/server/auth.js
new file mode 100644
index 00000000..56d6efc1
--- /dev/null
+++ b/src/server/auth.js
@@ -0,0 +1,22 @@
+var settings = require('./settings'),
+ auth = null
+
+if (settings.read('authentication')) {
+
+ var [name, pwd] = settings.read('authentication').split(':'),
+ httpAuth = require('http-auth')
+
+ auth = httpAuth.basic(
+ {
+ realm: 'Open Stage Control'
+ },
+ (username, password, callback) => {
+ // Custom authentication method.
+ callback(username === name && password === pwd)
+ }
+ )
+
+}
+
+
+module.exports = auth
diff --git a/src/server/callbacks.js b/src/server/callbacks.js
new file mode 100644
index 00000000..0c5e9f43
--- /dev/null
+++ b/src/server/callbacks.js
@@ -0,0 +1,467 @@
+var path = require('path'),
+ fs = require('fs'),
+ settings = require('./settings'),
+ osc = require('./osc'),
+ {ipc} = require('./server'),
+ {deepCopy} = require('./utils'),
+ theme = require('./theme')
+
+var widgetHashTable = {},
+ clipboard = {clipboard: null, idClipboard: null}
+
+module.exports = {
+
+ open(data, clientId) {
+ // client connected
+
+ ipc.send('connected')
+
+ var recentSessions = settings.read('recentSessions')
+
+ ipc.send('sessionList', recentSessions, clientId)
+ ipc.send('clipboard', clipboard, clientId)
+ ipc.send('serverTargets', settings.read('send'), clientId)
+
+ if (settings.read('load') && !data.hotReload) return this.sessionOpen({path: settings.read('load')}, clientId)
+
+ },
+
+ close(data, clientId) {
+ // client disconnected
+
+ },
+
+ destroyed(data, clientId) {
+ // client removed (timeout)
+
+ // clear osc data cache
+ if (widgetHashTable[clientId]) delete widgetHashTable[clientId]
+
+ },
+
+ clipboard(data, clientId) {
+ // shared clipboard
+
+ clipboard = data
+ ipc.send('clipboard', data, null, clientId)
+
+ },
+
+ sessionAddToHistory(data) {
+
+ var recentSessions = settings.read('recentSessions')
+
+ fs.lstat(data, (err, stats)=>{
+
+ if (err || !stats.isFile()) return
+
+ // add session to history
+ recentSessions.unshift(path.resolve(data))
+ // remove doubles from history
+ recentSessions = recentSessions.filter(function(elem, index, self) {
+ return index == self.indexOf(elem)
+ })
+
+ // history size limit
+ if (recentSessions.length > 10) recentSessions = recentSessions.slice(0, 10)
+
+ // save history
+ settings.write('recentSessions', recentSessions)
+
+ ipc.send('sessionList', recentSessions)
+
+ })
+ },
+
+ sessionRemoveFromHistory(data) {
+
+ var recentSessions = settings.read('recentSessions')
+ if (recentSessions.indexOf(data) > -1) {
+ recentSessions.splice(recentSessions.indexOf(data),1)
+ settings.write('recentSessions',recentSessions)
+ ipc.send('sessionList', recentSessions)
+ }
+
+ },
+
+ sessionSetPath(data, clientId) {
+ // store client's current session file path
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ if (!settings.read('read-only')) {
+ module.exports.sessionAddToHistory(data.path)
+ }
+
+ ipc.clients[clientId].sessionPath = data.path
+
+ ipc.send('setTitle', path.basename(data.path), clientId)
+
+ },
+
+ sessionOpen(data, clientId) {
+ // attempt to read session file
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ module.exports.fileRead(data, clientId, true, (result)=>{
+
+ ipc.clients[clientId].sessionPath = data.path // for resolving local file requests
+ ipc.send('sessionOpen', {path: data.path, session: result}, clientId)
+
+ })
+
+ },
+
+ sessionOpened(data, clientId) {
+ // session file opened successfully
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ if (settings.read('state')) {
+ var send = true
+ for (var id in ipc.clients) {
+ // only make the client send its osc state if there are no other active clients
+ if (id !== clientId && ipc.clients[id].connected()) {
+ send = false
+ }
+ }
+ var state = {
+ state: JSON.parse(fs.readFileSync(settings.read('state'), 'utf8')),
+ send: send
+ }
+ ipc.send('stateLoad', state, clientId)
+ }
+
+ ipc.send('stateSend', null, null, clientId)
+
+ module.exports.sessionSetPath({path: data.path}, clientId)
+
+ },
+
+ fileRead(data, clientId, ok, callback) {
+ // private function
+
+ if (!ok) return
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ fs.readFile(data.path, 'utf8', (err, result)=>{
+
+ var error
+
+ if (err) {
+ error = err
+ } else {
+ try {
+ result = JSON.parse(result)
+ callback(result)
+ } catch(err) {
+ error = err
+ }
+ }
+
+ if (error) ipc.send('error', `Could not open file (${error})`)
+
+ })
+
+ },
+
+ fileSave(data, clientId, ok, callback) {
+ // private function
+
+ if (!ok) return
+
+ if (!data.path || settings.read('remote-saving') && !RegExp(settings.read('remote-saving')).test(ipc.clients[clientId].address)) {
+
+ return ipc.send('notify', {
+ icon: 'save',
+ locale: 'remotesave_forbidden',
+ class: 'error'
+ }, clientId)
+
+ }
+
+ if (data.path) {
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ var root = settings.read('remote-root')
+ if (root && !data.path.includes(root)) {
+ console.error('(ERROR) Could not save: path outside of remote-root')
+ return ipc.send('notify', {
+ class: 'error',
+ locale: 'remotesave_fail',
+ message: ' (Could not save: path outside of remote-root)'
+ }, clientId)
+ }
+
+ try {
+ JSON.parse(data.session)
+ } catch(e) {
+ return console.error('(ERROR) Could not save: invalid file')
+ }
+
+ fs.writeFile(data.path, data.session, function(err, fdata) {
+
+ if (err) return ipc.send('notify', {
+ class: 'error',
+ locale: 'remotesave_fail',
+ message: err
+ }, clientId)
+
+
+ ipc.send('notify', {
+ icon: 'save',
+ locale: 'remotesave_success',
+ message: ' ('+ path.basename(data.path) +')'
+ }, clientId)
+
+ callback()
+
+ })
+
+ }
+
+ },
+
+ stateOpen(data, clientId) {
+ // attempt to open state file
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ module.exports.fileRead(data, clientId, true, (result)=>{
+
+ ipc.send('stateLoad', {state: result, path: data.path, send: true}, clientId)
+
+ })
+
+ },
+
+ sessionSave(data, clientId) {
+ // save session file (.json)
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ if (!path.basename(data.path).match(/.*\.json$/)) return console.error('(ERROR) Sessions must be saved as .json files')
+
+ module.exports.fileSave(data, clientId, true, ()=>{
+
+ console.log('(INFO) Session file saved in '+ data.path)
+
+ ipc.send('sessionSaved', clientId)
+
+ // reload session in other clients
+ for (var id in ipc.clients) {
+ if (id !== clientId && ipc.clients[id].sessionPath === data.path) {
+ module.exports.sessionOpen({path: data.path}, id)
+ }
+ }
+
+ module.exports.sessionSetPath({path: data.path}, clientId)
+
+ })
+
+ },
+
+ stateSave(data, clientId) {
+ // save state file (.json)
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ if (!path.basename(data.path).match(/.*\.state/)) return console.error('(ERROR) Statesaves must be saved as .state files')
+
+ module.exports.fileSave(data, clientId, true, ()=>{
+
+ console.log('(INFO) State file saved in '+ data.path)
+
+ })
+
+ },
+
+ syncOsc(shortdata, clientId) {
+ // sync osc (or midi) message with other clients
+
+ if (!(widgetHashTable[clientId] && widgetHashTable[clientId][shortdata.h])) return
+
+ var value = shortdata.v,
+ data = widgetHashTable[clientId][shortdata.h]
+
+ data = deepCopy(data)
+ for (var k in shortdata) {
+ data[k] = shortdata[k]
+ }
+
+ // only rawTarget will be used
+ delete data.target
+
+ data.args = data.preArgs ? data.preArgs.concat(value) : [value]
+
+ if (!data.noSync) ipc.send('receiveOsc', data, null, clientId)
+
+
+ },
+
+ sendOsc(shortdata, clientId) {
+ // send osc (or midi) message and sync with other clients
+
+ if (!(widgetHashTable[clientId] && widgetHashTable[clientId][shortdata.h])) return
+
+ var value = shortdata.v,
+ data = widgetHashTable[clientId][shortdata.h]
+
+ data = deepCopy(data)
+ for (var k in shortdata) {
+ data[k] = shortdata[k]
+ }
+
+ if (data.target) {
+
+ var targets = []
+
+ if (!shortdata.i && settings.read('send') && !shortdata.target) Array.prototype.push.apply(targets, settings.read('send'))
+ if (data.target) Array.prototype.push.apply(targets, data.target)
+
+ data.args = data.preArgs ? data.preArgs.concat(value) : [value]
+
+ for (var i in targets) {
+
+ if (targets[i] === 'self') {
+ ipc.send('receiveOsc',data,clientId)
+ continue
+ } else if (targets[i] === null) {
+ continue
+ }
+
+ var host = targets[i].split(':')[0],
+ port = targets[i].split(':')[1]
+
+ if (port) {
+
+ osc.send(host, port, data.address, data.args, data.typeTags, clientId)
+
+ }
+
+ }
+
+ }
+
+ if (!data.noSync) ipc.send('receiveOsc', data, null, clientId)
+
+ },
+
+ addWidget(data, clientId) {
+ // cache widget osc data to reduce bandwidth usage
+
+ if (!widgetHashTable[clientId]) {
+ widgetHashTable[clientId] = {}
+ }
+
+ if (!widgetHashTable[clientId][data.hash]) {
+ widgetHashTable[clientId][data.hash] = {}
+ }
+
+ var cache = widgetHashTable[clientId][data.hash],
+ widgetData = data.data
+
+ for (var k in widgetData) {
+ if ((k === 'target' || k === 'preArgs')) {
+ if (widgetData[k] !== '') {
+ cache[k] = Array.isArray(widgetData[k]) ? widgetData[k] : [widgetData[k]]
+ } else {
+ cache[k] = []
+ }
+ } else {
+ cache[k] = widgetData[k]
+ }
+ }
+
+ // store raw target for client sync widget matching
+ cache._rawTarget = widgetData.target
+
+ },
+
+ removeWidget(data, clientId) {
+ // clear widget osc data
+
+ delete widgetHashTable[clientId][data.hash]
+
+ },
+
+ reload(data) {
+ // (dev) hot reload
+ ipc.send('reload')
+
+ },
+
+ reloadCss() {
+ // (dev) hot css reload
+
+ theme.load()
+ ipc.send('reloadCss')
+ },
+
+ log(data) {
+ console.log(data)
+ },
+
+ error(data) {
+ console.error(data)
+ },
+
+ errorLog(data) {
+ console.error(data)
+ },
+
+ errorPopup(data) {
+ ipc.send('error', data)
+ },
+
+ listDir(data, clientId) {
+ // remote file browser backend
+
+ var p = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']
+
+ if (data.path) {
+ // Resolve '~' to user's home directory
+ if (data.path[0].startsWith('~')) {
+ p = data.path[0].replace( '~', p )
+ }
+ else {
+ p = path.resolve(...data.path)
+ }
+ //console.log(`Resolved path: ${p}`);
+ }
+
+ var root = settings.read('remote-root')
+ if (root && !p.includes(root)) p = root
+
+ fs.readdir(p, (err, files)=>{
+ if (err) {
+ ipc.send('notify', {class: 'error', message: err.message}, clientId)
+ throw err
+ } else {
+ var extRe = data.extension ? new RegExp('.*\\.' + data.extension + '$') : /.*/
+ var list = files.filter(x=>x[0] !== '.').map((x)=>{
+ var folder = false
+ try {
+ folder = fs.statSync(path.resolve(p, x)).isDirectory()
+ } catch(e) {}
+ return {
+ name: x,
+ folder
+ }
+ })
+ list = list.filter(x=>x.folder || x.name.match(extRe))
+ ipc.send('listDir', {
+ path: p,
+ files: list
+ }, clientId)
+ }
+ })
+
+
+ },
+
+
+}
diff --git a/src/server/docs-server.js b/src/server/docs-server.js
new file mode 100644
index 00000000..a8fd215f
--- /dev/null
+++ b/src/server/docs-server.js
@@ -0,0 +1,90 @@
+var EventEmitter = require('events').EventEmitter,
+ http = require('http'),
+ send = require('send'),
+ path = require('path'),
+ fs = require('fs'),
+ open = require('open'),
+ address = require('./address')
+
+class DocsServer extends EventEmitter {
+
+ constructor() {
+
+ super(...arguments)
+
+ this.baseUrl = path.resolve(__dirname + '/../docs')
+ this.home = '/docs/getting-started/introduction/'
+ this.server = null
+ this.started = false
+ this.port = 0
+
+ this.available = true
+ if (!fs.existsSync(path.join(this.baseUrl, 'index.html'))) {
+ console.error('(ERROR, DOCS) Documentation assets not found in the app\'s directory.')
+ this.available = false
+ }
+
+
+
+ }
+
+ start() {
+
+ if (this.started || !this.available) return
+
+ this.server = http.createServer(this.route.bind(this))
+ this.server.on('error', (e)=>{
+ console.error(`(ERROR, DOCS) ${e.message}`)
+ })
+ this.server.listen(0).on('listening', ()=>{
+ this.port = this.server.address().port
+ console.log('(INFO) Documentation server started, docs available at \n ' + address('http://', this.port).join('\n '))
+ this.emit('ready')
+
+ })
+ this.started = true
+
+ }
+
+ open() {
+
+ if (!this.started || !this.port) {
+ this.start()
+ this.on('ready', ()=>{
+ open(address('http://', this.port)[0] + this.home)
+ console.log('(INFO) Opening documentation with default browser...')
+ })
+ } else {
+ open(address('http://', this.port)[0] + this.home)
+ console.log('(INFO) Opening documentation with default browser...')
+ }
+
+ }
+
+ route(req, res) {
+
+ var url = req.url.replace(this.baseUrl, '').split('?')[0]
+
+ if (url[url.length-1] === '/') url += 'index.html'
+
+ if (url.indexOf('/fonts') === 0) url = '../assets' + url
+
+ url = path.join(this.baseUrl, url)
+
+
+ if (!fs.existsSync(url)) {
+ if (url.indexOf('index.html') !== -1) {
+ return send(req, path.join(this.baseUrl, '/404.html')).pipe(res)
+ } else {
+ res.writeHead(403)
+ res.end()
+ }
+ } else {
+ return send(req, url).pipe(res)
+ }
+
+ }
+
+}
+
+module.exports = DocsServer
diff --git a/src/server/electron-app.js b/src/server/electron-app.js
new file mode 100644
index 00000000..686369bb
--- /dev/null
+++ b/src/server/electron-app.js
@@ -0,0 +1,130 @@
+var {app, Menu, shell, BrowserWindow} = require('electron'),
+ settings = require('./settings'),
+ infos = require('../package.json')
+
+app.setPath('userData', settings.configPath)
+
+app.commandLine.appendSwitch('--touch-events')
+
+if (settings.read('disable-vsync')) {
+ app.commandLine.appendSwitch('--disable-gpu-vsync')
+}
+
+if (settings.read('disable-gpu')) {
+ app.disableHardwareAcceleration()
+ app._noGpu = true
+}
+
+if (settings.read('force-gpu')) {
+ app.commandLine.appendSwitch('--ignore-gpu-blacklist')
+}
+
+
+
+var template = [{
+ label: 'Edit',
+ submenu: [
+ {role: 'undo', accelerator: 'CmdOrCtrl+Z'},
+ {role: 'redo', accelerator: 'Shift+CmdOrCtrl+Z'},
+ {type: 'separator'},
+ {role: 'cut', accelerator: 'CmdOrCtrl+X'},
+ {role: 'copy', accelerator: 'CmdOrCtrl+C'},
+ {role: 'paste', accelerator: 'CmdOrCtrl+V'}
+ ]
+}]
+
+if (process.platform === 'darwin') {
+ // Add app menu (macOs)
+ template.unshift({
+ label: settings.infos.appName,
+ submenu: [
+ {
+ label: 'Hide ' + infos.productName,
+ accelerator: 'Command+H',
+ role: 'hide'
+ },
+ {
+ label: 'Hide Others',
+ accelerator: 'Command+Alt+H',
+ role: 'hideothers'
+ },
+ {
+ label: 'Show All',
+ role: 'unhide'
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: 'Quit',
+ accelerator: 'CmdOrCtrl+Q',
+ click: ()=>app.quit()
+ }
+ ]
+ })
+ template.push(
+ {
+ label: 'Window',
+ role: 'window',
+ submenu: [
+ {
+ label: 'Minimize',
+ accelerator: 'CmdOrCtrl+M',
+ role: 'minimize'
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: 'Close',
+ accelerator: 'CmdOrCtrl+W',
+ click: ()=>{
+ var win = BrowserWindow.getFocusedWindow()
+ if (win) win.close()
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: 'Bring All to Front',
+ role: 'front'
+ },
+ ]
+ },
+ {
+ label: 'Help',
+ role: 'help',
+ submenu: [
+ {
+ label: 'Documentation',
+ click: ()=>shell.openExternal(infos.homepage)
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: 'Report an Issue',
+ click: ()=>shell.openExternal(infos.repository.url + '/issues')
+ }
+ ]
+ }
+ )
+}
+
+app.on('before-quit',()=>{
+ process.exit()
+})
+
+app.on('ready',()=>{
+ var menu = Menu.buildFromTemplate(template)
+ Menu.setApplicationMenu(menu)
+})
+
+app.on('window-all-closed', function() {
+ if (process.platform !== 'darwin') {
+ app.quit()
+ }
+})
+
+module.exports = app
diff --git a/src/server/electron-window.js b/src/server/electron-window.js
new file mode 100644
index 00000000..2b50c20b
--- /dev/null
+++ b/src/server/electron-window.js
@@ -0,0 +1,163 @@
+var path = require('path'),
+ {BrowserWindow, dialog, shell, screen} = require('electron'),
+ shortcut = require('electron-localshortcut'),
+ app = require('./electron-app'),
+ settings = require('./settings'),
+ theme = require('./theme')
+
+module.exports = function(options={}) {
+
+ var window
+
+ window = new BrowserWindow({
+ title: options.title || settings.infos.appName,
+ icon: path.resolve(__dirname + '/../assets/logo.png'),
+ backgroundColor: options.color || theme.backgroundColor,
+ type: options.type,
+ useContentSize: true,
+ autoHideMenuBar: true,
+ webPreferences: {
+ nodeIntegration: !!options.node,
+
+ },
+ show: false,
+ })
+
+
+ // default geometry
+ var currentScreen = screen.getDisplayNearestPoint(screen.getCursorScreenPoint()),
+ screenSize = currentScreen.size,
+ width = options.width || screenSize.width,
+ height = options.height || screenSize.height,
+ bounds = currentScreen.bounds,
+ x = Math.ceil(bounds.x + ((bounds.width - width) / 2)),
+ y = Math.ceil(bounds.y + ((bounds.height - height) / 2))
+
+ window.setBounds({x, y, width, height})
+
+ // retreive last geometry
+ if (settings.read('geometry') && settings.read('geometry')[options.id]) {
+ var geometry = settings.read('geometry')[options.id],
+ mScreen = screen.getDisplayMatching(geometry)
+ if (intersectionArea(geometry, mScreen.bounds) > 20000) {
+ // don't load geometry if the window is not visible enough
+ window.setBounds(geometry)
+ }
+ }
+
+ window.once('ready-to-show', ()=>{
+ window.show()
+ })
+
+ window.webContents.once('page-title-updated', ()=>{
+ if (options.fullscreen) {
+ window.webContents.sendInputEvent({keyCode: 'F11', type: 'keyDown'})
+ }
+ if (app._noGpu) {
+ window.webContents.executeJavaScript(`
+ window.ELECTRON_NOGPU = true
+ `)
+ }
+ })
+
+
+ window.webContents.on('will-prevent-unload', (event)=>{
+ var choice = dialog.showMessageBoxSync(window, {
+ type: 'question',
+ buttons: ['Yes', 'No'],
+ title: 'Are you sure ?',
+ message: 'Unsaved data will be lost. Are you sure you want to quit?',
+ defaultId: 0,
+ cancelId: 1
+ })
+ if (choice === 0) {
+ event.preventDefault()
+ }
+ })
+
+
+ window.webContents.on('certificate-error', function(event, url, error, certificate, callback) {
+ if (error === 'net::ERR_CERT_AUTHORITY_INVALID') {
+ // self signed certificate is ok
+ event.preventDefault()
+ callback(true)
+ }
+ })
+
+ window.webContents.on('login', function(event, request, authInfo, callback) {
+ event.preventDefault()
+ var [name, pwd] = settings.read('authentication').split(':')
+ callback(name, pwd)
+ })
+
+ // window.webContents.on('will-navigate', (event)=>event.preventDefault())
+ window.webContents.on('new-window', (event, url)=>{
+ event.preventDefault()
+ shell.openExternal(url)
+ })
+
+
+ window.webContents.on('console-message', (event, level, message)=>{
+
+ if (level === 0 && message === 'ELECTRON.BLUR()') window.blur()
+
+ })
+
+ window.webContents.setVisualZoomLevelLimits(1, 1)
+
+ window.on('closed', function() {
+ window = null
+ })
+
+ window.setMenu(null)
+
+ window.loadURL(options.address)
+
+ if (process.platform !== 'darwin') {
+ // already registered in app menu on macOs
+ window.webContents.on('before-input-event', (e, input)=>{
+ // using before-input-event because electron-localshortcut
+ // gets azerty keyboards wrong (ctrl + z would also be catched)
+ if ((input.key === 'w' || input.key === 'W') && input.control && input.type === 'keyDown') {
+ window.close()
+ }
+ })
+ }
+
+ window.on('close', function() {
+ // save geometry
+ var geometry = settings.read('geometry') || {}
+ geometry[options.id] = window.getBounds()
+ settings.write('geometry', geometry)
+ })
+
+ if (options.shortcuts) {
+
+ shortcut.register(window,'CmdOrCtrl+R',function(){
+ window.reload()
+ })
+
+ shortcut.register(window,'F12',function(){
+ window.toggleDevTools()
+ })
+
+ } else {
+ shortcut.register(window,'CmdOrCtrl+R',function(e){
+ return false
+ })
+ }
+
+ return window
+
+}
+
+
+function intersectionArea(a, b) {
+ // intersectionArea between two rectangles
+
+ var width = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x),
+ height = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)
+
+ return width * height
+
+}
diff --git a/src/server/index.js b/src/server/index.js
new file mode 100644
index 00000000..134a6e84
--- /dev/null
+++ b/src/server/index.js
@@ -0,0 +1,216 @@
+require('source-map-support').install({handleUncaughtExceptions: false})
+
+var dev = process.argv[0].includes('node_modules'),
+ settings = require('./settings'),
+ docsServer, serverStarted
+
+
+function openDocs() {
+
+ if (!docsServer) {
+ var DocsServer = require('./docs-server')
+ docsServer = new DocsServer()
+ }
+
+ docsServer.open()
+
+}
+
+if (settings.read('docs')) return openDocs()
+
+
+function nodeMode() {
+
+ if (!settings.read('no-gui')) {
+ settings.write('no-gui', true, true)
+ console.warn('(INFO) Headless mode (--no-gui) enabled automatically (running with node)')
+ }
+
+ process.on('uncaughtException', (err)=>{
+ console.error('(ERROR) A JavaScript error occurred in the main process:')
+ console.error(err.stack)
+ })
+
+}
+
+if (process.title === 'node' || process.title === 'node.exe') {
+
+ nodeMode()
+
+} else {
+
+ try {
+
+ require('electron').dialog.showErrorBox = (title, err)=>{
+ console.error(title + ': ' + err)
+ }
+
+ } catch(e) {
+
+ nodeMode()
+
+ }
+
+}
+
+function start() {
+
+ if (!serverStarted) {
+
+ var server = require('./server'),
+ osc = require('./osc'),
+ callbacks = require('./callbacks'),
+ zeroconf = require('./zeroconf')
+
+ server.bindCallbacks(callbacks)
+
+ serverStarted = true
+ process.on('exit',()=>{
+ if (osc.midi) osc.midi.stop()
+ zeroconf.unpublishAll()
+ })
+
+ }
+
+}
+
+function openClient() {
+
+ var app = require('./electron-app')
+ var address = settings.appAddresses()[0]
+
+ var launch = ()=>{
+ var win = require('./electron-window')({address:address, shortcuts:true, fullscreen: settings.read('fullscreen'), id: 'client'})
+ win.on('error', ()=>{
+ console.log('ERR')
+ })
+ return win
+ }
+ if (app.isReady()) {
+ return launch()
+ } else {
+ app.on('ready',function(){
+ launch()
+ })
+ }
+
+}
+
+
+if (settings.cli) {
+
+ start()
+ if (!settings.read('no-gui')) openClient()
+
+
+} else {
+
+ var app = require('./electron-app'),
+ path = require('path'),
+ address = 'file://' + path.resolve(__dirname + '/../launcher/' + 'index.html'),
+ {ipcMain} = require('electron'),
+ {spawn} = require('child_process'),
+ launcher
+
+ process.on('exit',()=>{
+ if (global.serverProcess) global.serverProcess.kill()
+ })
+
+ app.on('ready',function(){
+ global.settings = settings
+ global.openDocs = openDocs
+ global.midilist = require('./midi').list
+ global.serverProcess = null
+ global.clientWindows = []
+ launcher = require('./electron-window')({address:address, shortcuts:dev, width:680, height:(40 + 200 + 20 + 24 * Object.keys(settings.options).filter(x=>settings.options[x].launcher !== false).length / 2), node:true, color:'#151a24', id: 'launcher'})
+ launcher.on('close', ()=>{
+ process.stdout.write = stdoutWrite
+ process.stderr.write = stderrWrite
+ if (process.log) process.log = processLog
+ })
+ })
+
+ let processLog = process.log,
+ stdoutWrite = process.stdout.write,
+ stderrWrite = process.stderr.write
+
+ if (process.log) {
+ process.log = function(string, encoding, fd) {
+ processLog.apply(process, arguments)
+ launcher.webContents.send('stdout', string)
+ }
+ }
+
+ process.stdout.write = function(string, encoding, fd) {
+ stdoutWrite.apply(process.stdout, arguments)
+ launcher.webContents.send('stdout', string)
+ }
+
+ process.stderr.write = function(string, encoding, fd) {
+ stderrWrite.apply(process.stderr, arguments)
+ launcher.webContents.send('stderr', string)
+ }
+
+ ipcMain.on('start',function(e, options){
+
+ var args = ['--', app.getAppPath(), '--no-gui']
+
+ // if (process.platform === 'win32') args.unshift('--') // not needed with ELECTRON_RUN_AS_NODE since '--' is always prepended
+ for (var k in settings.read('options')) {
+ args.push('--' + k)
+ var val = settings.read(k)
+ if (typeof val === 'object') {
+ args = args.concat(val)
+ } else if (typeof val !== 'boolean') {
+ args.push(val)
+ }
+ }
+
+ global.serverProcess = spawn(process.argv[0], args, {stdio: 'pipe', env: {...process.env, 'ELECTRON_RUN_AS_NODE':'1'}})
+ launcher.webContents.send('server-started')
+
+ if (!settings.read('no-gui')) {
+ var cb = (data)=>{
+ if (data.indexOf('Server started') > -1) {
+ global.clientWindows.push(openClient())
+ global.serverProcess.stdout.off('data', cb)
+ }
+ }
+ global.serverProcess.stdout.on('data', cb)
+ }
+
+ global.serverProcess.stdout.on('data', (data) => {
+ console.log(String(data).trim())
+ })
+
+ global.serverProcess.stderr.on('data', (data) => {
+ console.error(String(data).trim())
+ })
+
+ global.serverProcess.on('close', (code) => {
+ console.log('(INFO) Server stopped')
+ global.serverProcess = null
+ if (global.defaultClient) global.defaultClient.close()
+ if (!launcher.isDestroyed()) launcher.webContents.send('server-stopped')
+ })
+
+ })
+
+ ipcMain.on('stop',function(e, options){
+
+ if (global.serverProcess) global.serverProcess.kill()
+ for (var w of [...global.clientWindows]) {
+ if (w && !w.isDestroyed()) w.close()
+ }
+ global.clientWindows = []
+
+ })
+
+ ipcMain.on('openClient',function(e, options){
+
+ global.clientWindows.push(openClient())
+
+ })
+
+
+}
diff --git a/src/server/ipc/client.js b/src/server/ipc/client.js
new file mode 100644
index 00000000..481103cf
--- /dev/null
+++ b/src/server/ipc/client.js
@@ -0,0 +1,124 @@
+var EventEmitter = require('events').EventEmitter
+
+var hearbeatInterval = 25000,
+ hearbeatTimeout = 5000,
+ dieTimeout = 60000
+
+class Socket extends EventEmitter {
+
+ constructor(ws, id, address) {
+
+ super()
+
+ this.id = id
+
+ this.address = address.replace('::ffff:', '')
+
+ this.socket = null
+
+ this.sessionPath = ''
+
+ this.queue = []
+
+ this.hearbeat = undefined
+ this.hearbeatTimeout = undefined
+ this.on('pong', ()=>{
+ this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
+ })
+ this.on('ping', ()=>{
+ this.socket.send('["pong"]')
+ })
+
+ this.dieTimeout = undefined
+
+ this.open(ws)
+
+ }
+
+ open(ws) {
+
+ this.socket = ws
+
+ this.socket.onmessage = (e)=>{
+ this.receive(e.data)
+ }
+
+ this.socket.onclose = this.socket.onerror = ()=>{
+ if (!this.connected()) this.close()
+ }
+
+ this.dieTimeout = clearTimeout(this.dieTimeout)
+
+ this.hearbeat = setInterval(()=>{
+ if (!this.connected()) return
+ this.socket.send('["ping"]')
+ this.hearbeatTimeout = setTimeout(()=>{
+ if (this.connected()) this.socket.close()
+ }, hearbeatTimeout)
+ }, hearbeatInterval)
+
+ }
+
+ close() {
+
+ this.hearbeat = clearInterval(this.hearbeat)
+ this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
+ this.dieTimeout = clearTimeout(this.dieTimeout)
+
+ this.dieTimeout = setTimeout(()=>{
+
+ this.emit('destroyed')
+
+ }, dieTimeout)
+
+ }
+
+ connected() {
+
+ return this.socket.readyState == this.socket.OPEN
+
+ }
+
+ receive(message) {
+
+ if (typeof message == 'string') {
+
+ var packet = JSON.parse(message)
+
+ if (Array.isArray(packet) && typeof packet[0] == 'string') {
+
+ this.emit(packet[0], packet[1])
+
+ }
+
+ }
+
+ }
+
+ send(event, data) {
+
+ var packet = JSON.stringify([event, data])
+
+ if (this.connected()) {
+ this.socket.send(packet)
+ } else {
+ this.queue.push(packet)
+ }
+
+ }
+
+ flush(){
+
+ for (var i in this.queue) {
+
+ if (this.connected()) this.socket.send(this.queue[i])
+
+ }
+
+ this.queue = []
+
+ }
+
+}
+
+module.exports = Socket
diff --git a/src/server/ipc/server.js b/src/server/ipc/server.js
new file mode 100644
index 00000000..9be982df
--- /dev/null
+++ b/src/server/ipc/server.js
@@ -0,0 +1,71 @@
+var EventEmitter = require('events').EventEmitter,
+ WebSocketServer = require('ws').Server,
+ Client = require('./client'),
+ settings = require('../settings')
+
+class Ipc extends EventEmitter {
+
+ constructor(server) {
+
+ super()
+
+ this.clients = {}
+ this.server = null
+
+ this.server = new WebSocketServer({server: server})
+
+ this.server.on('connection', (socket, req)=>{
+
+ if (settings.read('authentication')) {
+ if (!req.headers.authorization) return
+ if (req.headers.authorization.search('Basic ') !== 0) return
+ var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString()
+ if (settings.read('authentication') !== auth) {
+ console.log(`(WARNING) Client connexion refused for ${req.connection.remoteAddress} (authentication failed)`)
+ socket.close()
+ return
+ }
+ }
+
+ var id = req.url.split('/').pop()
+
+ if (!id) return
+
+ if (!this.clients[id]) {
+
+ var client = new Client(socket, id, req.connection.remoteAddress)
+ this.clients[id] = client
+
+ this.emit('connection', client)
+
+ client.on('destroyed', ()=>{
+ delete this.clients[id]
+ })
+
+ } else {
+
+ this.clients[id].open(socket)
+ this.clients[id].flush()
+
+ }
+
+ })
+
+ }
+
+ send(event, data, id, except) {
+
+ var clients = id ? [this.clients[id]] : this.clients
+
+ for (var k in clients) {
+ if (!except || this.clients[k] != this.clients[except]) {
+ if (clients[k]) clients[k].send(event, data)
+ }
+ }
+
+ }
+
+
+}
+
+module.exports = Ipc
diff --git a/src/server/midi.js b/src/server/midi.js
new file mode 100644
index 00000000..eccb098b
--- /dev/null
+++ b/src/server/midi.js
@@ -0,0 +1,108 @@
+var {PythonShell} = require('python-shell'),
+ settings = require('./settings'),
+ midiVersion = '1.2.0'
+
+var pythonOptions = {
+ scriptPath:__dirname,
+ mode:'text',
+}
+
+class MidiConverter {
+
+ constructor() {
+
+ var pythonPath = settings.read('midi').filter(x=>x.includes('path=')).map(x=>x.split('=')[1])[0]
+
+ this.py = new PythonShell('python/midi.py', Object.assign({
+ args: [
+ settings.read('debug') ? 'debug' : '',
+ ...settings.read('midi')
+ ],
+ pythonPath
+ }, pythonOptions))
+
+ this.py.childProcess.on('error', (e)=>{
+ if (e.code === 'ENOENT') {
+ console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
+ } else {
+ console.error(`(ERROR, MIDI) ${e.message}`)
+ }
+ })
+
+ }
+
+ send(data) {
+
+ var args = []
+ for (let i in data.args) {
+ args.push(data.args[i].value)
+ }
+
+ this.py.send(JSON.stringify([data.port, data.address, ...args]))
+
+ }
+
+ stop() {
+
+ this.py.childProcess.kill()
+
+ }
+
+ init(receiveOsc) {
+
+ this.receiveOsc = receiveOsc
+ this.py.on('message', (message)=>{
+ MidiConverter.parseIpc(message, this)
+ })
+
+ }
+
+ static parseIpc(message, instance) {
+
+ // console.log(message)
+ var name, data
+ try {
+ [name, data] = JSON.parse(message)
+ } catch (err) {
+ if (settings.read('debug')) console.error(`(DEBUG, MIDI) Unparsed python log:\n ${message}`)
+ }
+ if (name == 'log') {
+ if (data.indexOf('ERROR') > -1) {
+ console.error(data)
+ } else {
+ console.log(data)
+ }
+ } else if (name == 'osc') {
+ instance.receiveOsc(data)
+ } else if (name == 'error') {
+ console.error('(ERROR, MIDI) ' + data)
+ if (instance) instance.stop()
+ } else if (name == 'version' && data != midiVersion) {
+ console.error(`(WARNING, MIDI) binary version mismatch (${data} installed, ${midiVersion} expected)`)
+ }
+
+ }
+
+ static list() {
+
+ var pythonPath = settings.read('midi') ? settings.read('midi').filter(x=>x.includes('path=')).map(x=>x.split('=')[1])[0] : undefined
+
+ PythonShell.run('python/midi.py', Object.assign({pythonPath: pythonPath, args: ['list-only']}, pythonOptions), function(e, results) {
+ if (e) {
+ if (e.code === 'ENOENT') {
+ console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
+ } else {
+ console.error(`(ERROR, MIDI) ${e.message}`)
+ }
+ }
+
+ for (let r of results) {
+ MidiConverter.parseIpc(r)
+ }
+ })
+
+ }
+
+}
+
+module.exports = MidiConverter
diff --git a/src/server/options.js b/src/server/options.js
new file mode 100644
index 00000000..0f265e28
--- /dev/null
+++ b/src/server/options.js
@@ -0,0 +1,97 @@
+var fs = require('fs')
+
+module.exports = {
+ 's': {alias: 'send', type: 'array', describe: 'default targets for all widgets (ip: port / domain: port / midi: port_name pairs)',
+ check: (s)=>{
+ return s.some(item=>!item.match(/^[^:]*:[0-9]{4,5}$/) && !item.match(/^midi:.*$/)) ?
+ 'Targets must be ip:port or hostname:port pairs (port must be >= 1024) or midi:port_name pairs' : true
+ }
+ },
+ 'l': {alias: 'load', type: 'string', file: {name: 'OSC Session (.json)', extensions: ['json']}, describe: 'session file to load (.json)',
+ check: (arg)=>{
+ return fs.existsSync(arg) ? true : 'Session file not found: ' + arg
+ }
+ },
+ 'state': {type: 'string', file: {name: 'OSC State (.state)', extensions: ['state']}, describe: 'state file to load (.state)',
+ check: (arg)=>{
+ return fs.existsSync(arg) ? true : 'State file not found: ' + arg
+ }
+ },
+ 'c': {alias: 'custom-module', type: 'string', file: {name: 'OSC Custom module (.js)', extensions: ['js']}, describe: 'custom module file to load (.js)',
+ check: (arg)=>{
+ return fs.existsSync(arg) ? true : 'Custom module file not found: ' + arg
+ },
+ },
+ 'p': {alias: 'port', type: 'number', describe: 'http port of the server (default to 8080)',
+ check: (p)=>{
+ return (!isNaN(p) && p > 1023 && parseInt(p)===p) ?
+ true : 'Port must be an integer >= 1024'
+ }
+ },
+ 'o': {alias: 'osc-port', type: 'number', describe: 'osc input port (default to --port)',
+ check: (o)=>{
+ return (!isNaN(o) && o > 1023 && parseInt(o)===o) ?
+ true : 'Port must be an integer >= 1024'
+ }
+ },
+ 'tcp-port': {type: 'number', describe: 'tcp server input port',
+ check: (t, argv)=>{
+ var h = argv['port']
+ if (t === h) return 'Tcp input port must different from --port'
+ return (!isNaN(t) && t > 1023 && parseInt(t)===t) ?
+ true : 'Port must be an integer >= 1024'
+ }
+ },
+ 'tcp-targets': {type: 'array', describe: 'tcp servers to connect to (ip: port pairs), does not susbtitute for --send',
+ check: (s, argv)=>{
+ if (!argv['tcp-port']) return '--tcp-port must be set'
+ return s.some(item=>!item.match(/^[^:]*:[0-9]{4,5}$/)) ?
+ 'Targets must be ip:port or hostname:port pairs (port must be >= 1024)' : true
+ }
+ },
+ 'm': {alias: 'midi', type: 'array', describe: 'midi router settings',
+ check: (o)=>{
+ var err = o.filter(item=>!item.match(/^(list|debug|jack|sysex|mtc|pc_offset|path=(.*)|[^:]+:(virtual|[^,]+,[^,]+))$/))
+ return err.length ? `Invalid option${err.length > 1 ? 's' : ''}: ${err.join(', ')}` : true
+ }
+ },
+ 'd': {alias: 'debug', type: 'boolean', describe: 'log received osc messages in the console'},
+ 'n': {alias: 'no-gui', type: 'boolean', describe: 'disable default gui'},
+ 'fullscreen': {type: 'boolean', describe: 'launch in fullscreen mode (only affects the default client gui)'},
+ 't': {alias: 'theme', type: 'array', describe: 'theme name or path (multiple values allowed)'},
+ 'client-options': {type: 'array', describe: 'client options (opt=value pairs)',
+ check: (o)=>{
+ return o.some(item=>!item.match(/^[^=]*=[^=]*$/)) ?
+ 'Options must be key=value pairs' : true
+ }
+ },
+ 'disable-vsync': {type: 'boolean', describe: 'disable gui\'s vertical synchronization', restart: true},
+ 'force-gpu': {type: 'boolean', describe: 'ignore chrome\'s gpu blacklist', restart: true},
+ 'read-only': {type: 'boolean', describe: 'disable session editing and session history changes'},
+ 'remote-saving': {type: 'string', describe: 'disable remote session saving for hosts that don\'t match the regular expression',
+ check: (r, argv)=>{
+ var msg = true
+ try {
+ RegExp(r)
+ } catch (e) {
+ msg = e
+ }
+ return msg
+ }
+ },
+ 'remote-root': {type: 'string', describe: 'set remote file browsing root folder', file: {folder: true}},
+ 'authentication': {type: 'string', describe: 'restrict access to "user:password" (remote clients will be prompted for these credentials)',
+ check: (a, argv)=>{
+ return a.match(/[^:]*:[^:]+/) ? true : 'Auth must be a user:password pair.'
+ }
+ },
+ 'instance-name': {type: 'string', describe: 'used to differenciate multiple instances in a zeroconf network'},
+ 'use-ssl': {type: 'boolean', describe: 'set to true to use HTTPS protocol instead of HTTP (a self-signed certificate will be created)'},
+
+ // cli only
+ 'disable-gpu': {type: 'boolean', describe: 'disable hardware acceleration', launcher: false},
+ 'inspect': {type: 'boolean', describe: 'enable node/electron inspector', launcher: false},
+ 'cache-dir': {type: 'string', describe: 'override default cache directory', launcher: false},
+ 'config-file': {type: 'string', describe: 'override default config file (defaults to cache-dir/config.json)', launcher: false},
+ 'docs': {type: 'boolean', describe: 'serve documentation website locally and open it with the system\'s default browser', launcher: false}
+}
diff --git a/src/server/osc/index.js b/src/server/osc/index.js
new file mode 100644
index 00000000..88140a71
--- /dev/null
+++ b/src/server/osc/index.js
@@ -0,0 +1,303 @@
+var path = require('path'),
+ ipc = require('../server').ipc,
+ settings = require('../settings'),
+ tcpInPort = settings.read('tcp-port'),
+ debug = settings.read('debug'),
+ vm = require('vm'),
+ fs = require('fs'),
+ midi = settings.read('midi') ? require('../midi') : false,
+ oscUDPServer = require('./udp'),
+ oscTCPServer = require('./tcp'),
+ EventEmitter = require('events').EventEmitter
+
+
+if (midi) midi = new midi()
+
+class OscServer {
+
+ constructor(){
+
+ this.customModuleEventEmitter = new EventEmitter()
+ this.customModule = (()=>{
+
+ var customModule = settings.read('custom-module')
+
+ if (!customModule) return false
+
+ var file = (()=>{
+ try {
+ return fs.readFileSync(customModule, 'utf8')
+ } catch(err) {
+ console.error('(ERROR) Custom module not found: ' + customModule)
+ return false
+ }
+ })(),
+ mod,
+ context = vm.createContext({
+ console,
+ sendOsc: this.sendOsc.bind(this),
+ receiveOsc: this.receiveOsc.bind(this),
+ send: (host, port, address, ...args)=>{
+ this.sendOsc({host, port, address, args:args.map(x=>this.parseArg(x))})
+ },
+ receive: (host, port, address, ...args)=>{
+ if (host[0] === '/') {
+ // host and port can be skipped
+ if (address !== undefined) args.unshift(address)
+ if (port !== undefined) args.unshift(port)
+ address = host
+ host = port = undefined
+ }
+ var lastArg = args[args.length - 1],
+ options = {}
+ if (typeof lastArg === 'object' && lastArg !== null && lastArg.clientId !== undefined) {
+ options = args.pop()
+ }
+ this.receiveOsc({host, port, address, args:args.map(x=>this.parseArg(x))}, options.clientId)
+ },
+ loadJSON: (url)=>{
+ if (url.split('.').pop() === 'json') {
+ try {
+ url = path.resolve(path.dirname(customModule), url)
+ return JSON.parse(fs.readFileSync(url, 'utf8'))
+ } catch(e) {
+ console.error('(ERROR) could not load json file from ' + url)
+ console.error(e.message)
+ }
+ } else {
+ console.error('(ERROR) unauthorized file type for loadJSON')
+ }
+ },
+ saveJSON: (url, data)=>{
+ if (url.split('.').pop() === 'json') {
+ url = path.resolve(path.dirname(customModule), url)
+ try {
+ return fs.writeFileSync(url, JSON.stringify(data, null, ' '))
+ } catch(e) {
+ console.error('(ERROR) could not save json file to ' + url)
+ console.error(e.message)
+ }
+ } else {
+ console.error('(ERROR) unauthorized file type for saveJSON')
+ }
+ },
+ app: this.customModuleEventEmitter,
+ setTimeout, clearTimeout,
+ setInterval, clearInterval,
+ settings,
+ module: {},
+ })
+
+ try {
+ // remove require function (not needed at runtime)
+ // wrong: this.constructor.constructor("return process")().mainModule.require
+ process.mainModule.require = process.dlopen = null
+ // run
+ mod = vm.runInContext(file, context, {
+ filename: customModule
+ })
+ if (context.module.exports) mod = context.module.exports
+ } catch(err) {
+ console.error(err)
+ return false
+ }
+
+ return mod
+
+ })()
+
+
+ }
+
+ parseArg(arg, type){
+
+ if (arg === null) return null
+
+ if (type && type[0].match(/[bhtdscrmifTFNI]/)) {
+
+ type = type[0]
+
+ switch (type) {
+ case 'i':
+ return {type: type, value: parseInt(arg)}
+ case 'd':
+ case 'f':
+ return {type: type, value: parseFloat(arg)}
+ case 'T':
+ case 'F':
+ case 'N':
+ return {type: type}
+ default:
+ return {type: type, value: arg}
+
+
+ }
+
+ }
+
+ switch (typeof arg) {
+ case 'number':
+ return {type: 'f', value: arg}
+ case 'boolean':
+ return {type: arg ? 'T' : 'F'}
+ case 'string':
+ return {type: 's', value:arg}
+ case 'object':
+ if (arg.type) return arg
+ default:
+ return {type: 's', value:JSON.stringify(arg)}
+ }
+ }
+
+ sendOsc(data){
+
+ if (!data) return
+
+ if (data.host == 'midi') {
+
+ if (midi) midi.send(data)
+
+ } else {
+
+ if (typeof data.address !== 'string' || data.address[0] !== '/') {
+ console.error('(ERROR, OSC) Malformed address: ' + data.address)
+ return
+ }
+
+ if (tcpInPort && oscTCPServer.clients[data.host] && oscTCPServer.clients[data.host][data.port]) {
+
+ oscTCPServer.clients[data.host][data.port].send({
+ address: data.address,
+ args: data.args
+ })
+
+ } else {
+
+ oscUDPServer.send({
+ address: data.address,
+ args: data.args
+ }, data.host, data.port)
+
+ }
+
+ if (debug) console.log('(DEBUG, OSC) Out: ',{address:data.address, args: data.args}, 'To: ' + data.host + ':' + data.port)
+
+ }
+
+
+ }
+
+ receiveOsc(data, clientId){
+
+ if (!data) return
+
+ for (var i in data.args) {
+ data.args[i] = data.args[i].value
+ }
+
+ if (data.args.length==1) data.args = data.args[0]
+
+ ipc.send('receiveOsc', data, clientId)
+
+ if (debug) console.log('(DEBUG, OSC) In: ', {address:data.address, args: data.args}, 'From: ' + data.host + ':' + data.port)
+
+ }
+
+
+ oscInFilter(data){
+ if (this.customModule.oscInFilter) {
+ return this.customModule.oscInFilter(data)
+ } else {
+ return data
+ }
+ }
+ oscOutFilter(data){
+ if (this.customModule.oscOutFilter) {
+ return this.customModule.oscOutFilter(data)
+ } else {
+ return data
+ }
+ }
+
+ oscInHandler(msg, timetag, info){
+ var data = this.oscInFilter({address: msg.address, args: msg.args, host: info.address, port: info.port})
+ if (!data) return
+ this.receiveOsc(data)
+ }
+
+ oscInHandlerWrapper(msg, timetag, info) {
+ var delay = timetag? Math.max(0,timetag.native - Date.now()) : 0
+ if (delay) {
+ setTimeout(()=>{
+ this.oscInHandler(msg, timetag, info)
+ }, delay)
+ } else {
+ this.oscInHandler(msg, timetag, info)
+ }
+ }
+
+
+
+ init(){
+
+ if (midi) midi.init((data)=>{
+
+ data = this.oscInFilter({address: data.address, args: data.args, host: data.host, port: data.port})
+
+ if (!data) return
+
+ this.receiveOsc(data)
+
+ })
+
+ oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this))
+ oscUDPServer.open()
+
+ if (settings.read('tcp-port')) {
+ oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this))
+ oscTCPServer.open()
+ }
+
+ if (this.customModule.init) {
+ this.customModule.init()
+ }
+
+ }
+
+
+}
+
+
+var oscServer = new OscServer()
+oscServer.init()
+
+module.exports = {
+ server: oscServer,
+ send: function(host, port, address, args, typeTags, clientId) {
+
+ var message = []
+
+ if (!Array.isArray(args)) args = [args]
+
+ if (typeof args === 'object' && args !== null) {
+
+ var typeTag,
+ arg
+
+ for (var i = 0; i < args.length; i++) {
+
+ typeTag = typeTags[i] || typeTag
+ arg = oscServer.parseArg(args[i], typeTag)
+
+ if (arg !== null) message.push(arg)
+
+ }
+ }
+
+ var data = oscServer.oscOutFilter({address:address, args: message, host: host, port: port, clientId: clientId})
+
+ oscServer.sendOsc(data)
+
+ },
+ midi:midi
+}
diff --git a/src/server/osc/osc.js b/src/server/osc/osc.js
new file mode 100644
index 00000000..4da82ea9
--- /dev/null
+++ b/src/server/osc/osc.js
@@ -0,0 +1,7 @@
+var osc = require('osc/src/osc.js'),
+ transports = require('osc/src/platforms/osc-node.js')
+
+osc.UDPPort = transports.UDPPort
+osc.TCPSocketPort = transports.TCPSocketPort
+
+module.exports = osc
diff --git a/src/server/osc/tcp.js b/src/server/osc/tcp.js
new file mode 100644
index 00000000..e9207ab7
--- /dev/null
+++ b/src/server/osc/tcp.js
@@ -0,0 +1,146 @@
+var osc = require('./osc'),
+ EventEmitter = require('events').EventEmitter,
+ settings = require('../settings'),
+ zeroconf = require('../zeroconf'),
+ tcpInPort = settings.read('tcp-port'),
+ tcpTargets = settings.read('tcp-targets'),
+ net = require('net')
+
+class OscTCPClient extends EventEmitter {
+
+ constructor(options) {
+
+ super()
+
+ this.options = options
+ this.remoteAddress = options.address
+ this.remotePort = options.port
+
+ this.open()
+
+ }
+
+ open() {
+
+ this.port = new osc.TCPSocketPort(this.options)
+
+ this.port.on('error', (err)=>{
+ console.error(`(ERROR, TCP) ${err.message}`)
+ })
+
+ this.port.on('close', (hadErr)=>{
+ console.log(`(TCP) Connection closed (${this.remoteAddress}:${this.remotePort})`)
+ if (!this.options.socket) {
+ console.log(`(TCP) Attempting reconnection in 5s (${this.remoteAddress}:${this.remotePort})`)
+ this.reconnect()
+ } else {
+ this.emit('die')
+ }
+ })
+
+ this.port.on('message', (msg, timetag)=>{
+ this.emit('message', msg, timetag, {address: this.remoteAddress, port: this.remotePort})
+ })
+
+ this.port.on('ready', ()=>{
+ console.log(`(TCP) Connection established (${this.remoteAddress}:${this.remotePort})`)
+ })
+
+ if (!this.options.socket) {
+
+ this.port.open()
+
+ } else {
+
+ this.port.emit('ready')
+
+ }
+
+ }
+
+ reconnect() {
+
+ setTimeout(()=>{
+ this.open()
+ }, 5000)
+
+ }
+
+ send(msg) {
+
+ this.port.send(msg)
+
+ }
+
+
+
+}
+
+class OscTCPServer extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.clients = {}
+
+ }
+
+ bindSocket(socket) {
+
+ this.addClient(new OscTCPClient({
+ metadata: true,
+ socket: socket,
+ address: socket.remoteAddress.replace('::ffff:', ''),
+ port: socket.remotePort
+ }))
+
+ }
+
+ addClient(client) {
+
+ this.clients[client.remoteAddress] = this.clients[client.remoteAddress] || {}
+ this.clients[client.remoteAddress][client.remotePort] = client
+
+ client.on('message', (msg, timetag, info)=>{
+ this.emit('message', msg, timetag, info)
+ })
+
+ client.on('die', (hadError)=>{
+ if (this.clients[client.remoteAddress]) delete this.clients[client.remoteAddress][client.remotePort]
+ })
+
+ }
+
+
+ open() {
+
+ this.server = net.createServer(this.bindSocket.bind(this))
+ this.server.listen({port: tcpInPort})
+
+ for (var i in tcpTargets) {
+
+ this.addClient(new OscTCPClient({
+ metadata: true,
+ address: tcpTargets[i].split(':')[0],
+ port: tcpTargets[i].split(':')[1]
+ }))
+
+ }
+
+ zeroconf.publish({
+ name: settings.infos.appName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
+ protocol: 'tcp',
+ type: 'osc',
+ port: tcpInPort
+ }).on('error', (e)=>{
+ console.error(`Error: Zeroconf: ${e.message}`)
+ })
+
+
+ }
+}
+
+var oscTCPServer = new OscTCPServer()
+
+module.exports = oscTCPServer
diff --git a/src/server/osc/udp.js b/src/server/osc/udp.js
new file mode 100644
index 00000000..2eab0b41
--- /dev/null
+++ b/src/server/osc/udp.js
@@ -0,0 +1,28 @@
+var osc = require('./osc'),
+ settings = require('../settings'),
+ zeroconf = require('../zeroconf'),
+ oscInPort = settings.read('osc-port') || settings.read('port') || 8080
+
+var oscUDPServer = new osc.UDPPort({
+ localAddress: '0.0.0.0',
+ localPort: oscInPort,
+ metadata: true,
+ broadcast: true
+})
+
+oscUDPServer.on('error', function(e) {
+ if (e.code === 'EADDRINUSE') {
+ console.error(`(ERROR, UDP) could not open port ${oscInPort} (already in use) `)
+ } else {
+ console.error(`(ERROR, UDP) ${e.message}`)
+ }
+})
+
+zeroconf.publish({
+ name: settings.infos.appName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
+ protocol: 'udp',
+ type: 'osc',
+ port: oscInPort
+})
+
+module.exports = oscUDPServer
diff --git a/src/server/server.js b/src/server/server.js
new file mode 100644
index 00000000..ad07b157
--- /dev/null
+++ b/src/server/server.js
@@ -0,0 +1,179 @@
+var settings = require('./settings'),
+ http = require('http')
+
+function createServer(route) {
+ if (settings.read('use-ssl')) {
+ http = require('https')
+ require('./ssl')
+ return http.createServer(settings.read('ssl-certificate'), route)
+
+ } else {
+ return http.createServer(route)
+ }
+}
+
+var urlparser = require('url'),
+ path = require('path'),
+ fs = require('fs'),
+ send = require('send'),
+ replaceStream = require('replacestream'),
+ auth = require('./auth'),
+ server = createServer(auth ? auth.check(httpRoute) : httpRoute),
+ Ipc = require('./ipc/server'),
+ ipc = new Ipc(server),
+ theme = require('./theme').init(),
+ zeroconf = require('./zeroconf'),
+ prod = !process.argv[0].includes('node_modules'),
+ osc = {},
+ clients = {},
+ httpCheckTimeout
+
+
+var clientOptions = {}
+if (settings.read('client-options')) {
+ for (var o of settings.read('client-options')) {
+ if (!o.includes('=')) continue
+ var [k, v] = o.split('=')
+ clientOptions[k] = v
+ }
+}
+
+
+function httpRoute(req, res) {
+
+ res.sendFile = (path)=>{
+ var fpath = path.split('?')[0]
+ if (!fs.existsSync(fpath)) throw `File "${fpath}" not found.`
+ return send(req, fpath).pipe(res)
+ }
+
+ var url = req.url
+
+ if (url === '/' || url.indexOf('/?') === 0) {
+
+ var ip = req.connection.remoteAddress.replace('::ffff:', '')
+
+ fs.createReadStream(path.resolve(__dirname + '/../client/index.html'))
+ .pipe(replaceStream('