diff --git a/Gruntfile.coffee b/Gruntfile.coffee index 0756bbd..3b81dd7 100644 --- a/Gruntfile.coffee +++ b/Gruntfile.coffee @@ -141,7 +141,7 @@ module.exports = (grunt) -> watch: scripting: files: ['src/scripting/**/*', '!node_modules'] - tasks: ['build-scripting'] + tasks: ['build:scripting'] core: files: ['src/**/*', '!node_modules', '!src/scripting/**/*'] tasks: ['build'] diff --git a/dist/CommentCoreLibrary.js b/dist/CommentCoreLibrary.js index 56766b3..f205967 100644 --- a/dist/CommentCoreLibrary.js +++ b/dist/CommentCoreLibrary.js @@ -1106,51 +1106,112 @@ var CommentManager = (function() { })(); /** - * Comment Filters Module Simplified (only supports modifiers & types) + * Comment Filters Module Simplified * @license MIT * @author Jim Chen */ -function CommentFilter() { - this.modifiers = []; - this.runtime = null; - this.allowTypes = { - "1":true, - "4":true, - "5":true, - "6":true, - "7":true, - "8":true, - "17":true - }; - this.doModify = function(cmt){ - for(var k=0;k 0) { + var item = path.shift(); + if (item === '') { + continue; + } + if (extracted.hasOwnProperty(item)) { + extracted = extracted[item]; + } + if (extracted === null || typeof extracted === 'undefined') { + extracted = null; + break; + } + } + if (extracted === null) { + // Null precondition implies anything + return true; + } + switch (rule.op) { + case '~': + case 'regexp': + return (new RegExp(rule.value)).test(extracted.toString()); + case '=': + case 'eq': + return rule.value === extracted.toString(); + case 'NOT': + return !_match(rule.value, cmtData); + case 'AND': + if (Array.isArray(rule.value)) { + return rule.value.every(function (r) { + return _match(r, cmtData); + }); + } else { + return false; + } + case 'OR': + if (Array.isArray(rule.value)) { + return rule.value.some(function (r) { + return _match(r, cmtData); + }); + } else { + return false; + } + default: + return false; + } + } + + function CommentFilter() { + this.rules = []; + this.modifiers = []; + this.allowUnknownTypes = true; + this.allowTypes = { + '1': true, + '2': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '17': true + }; + } + + CommentFilter.prototype.doModify = function (cmt) { + for (var k=0; k < this.modifiers.length; k++) { + cmt = this.modifiers[k](cmt); + } + return cmt; + }; + + CommentFilter.prototype.beforeSend = function (cmt) { + return cmt; + } + + CommentFilter.prototype.doValidate = function (cmtData) { + if (cmtData.mode.toString() in this.allowTypes && + !this.allowTypes[cmtData.mode.toString()]) { + return false; + } + return this.rules.every(function (rule) { + // Decide if matched + var matched = _match(rule, cmtData); + return rule.mode === 'accept' ? matched : !matched; + }); + }; + + CommentFilter.prototype.addRule = function (rule) { + if (rule.mode !== 'accept' && rule.mode !== 'reject') { + throw new Error('Rule must be of accept type or reject type.'); + } + this.rules.push(rule); + }; + + CommentFilter.prototype.addModifier = function (f) { + this.modifiers.push(f); + }; +})(); /** * Comment Provider diff --git a/dist/CommentCoreLibrary.min.js b/dist/CommentCoreLibrary.min.js index 16b7939..af60a00 100644 --- a/dist/CommentCoreLibrary.min.js +++ b/dist/CommentCoreLibrary.min.js @@ -1 +1 @@ -/*!Copyright(c) CommentCoreLibrary (//github.com/jabbany/CommentCoreLibrary) - Licensed under the MIT License */function CommentFilter(){this.modifiers=[],this.runtime=null,this.allowTypes={1:!0,4:!0,5:!0,6:!0,7:!0,8:!0,17:!0},this.doModify=function(a){for(var b=0;b=0)return a.length;for(var d=0,e=0,f=0,g=a.length-1;d<=g;){if(e=Math.floor((g+d+1)/2),f++,c(b,a[e-1])>=0&&c(b,a[e])<0)return e;if(c(b,a[e-1])<0)g=e-1;else{if(!(c(b,a[e])>=0))throw new Error("Program Error. Inconsistent comparator or unsorted array!");d=e}if(f>1500)throw new Error("Iteration depth exceeded. Inconsistent comparator or astronomical dataset!")}return-1},a.binsert=function(b,c,d){var e=a.bsearch(b,c,d);return b.splice(e,0,c),e},a}(),CommentUtils;!function(a){var b=function(){function a(a){if(this._internalArray=null,!Array.isArray(a))throw new Error("Not an array. Cannot construct matrix.");if(16!=a.length)throw new Error("Illegal Dimensions. Matrix3D should be 4x4 matrix.");this._internalArray=a}return Object.defineProperty(a.prototype,"flatArray",{get:function(){return this._internalArray.slice(0)},set:function(a){throw new Error("Not permitted. Matrices are immutable.")},enumerable:!0,configurable:!0}),a.prototype.isIdentity=function(){return this.equals(a.identity())},a.prototype.dot=function(b){for(var c=this._internalArray.slice(0),d=b._internalArray.slice(0),e=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],f=0;f<4;f++)for(var g=0;g<4;g++)for(var h=0;h<4;h++)e[4*f+g]+=c[4*f+h]*d[4*h+g];return new a(e)},a.prototype.equals=function(a){for(var b=0;b<16;b++)if(this._internalArray[b]!==a._internalArray[b])return!1;return!0},a.prototype.toCss=function(){for(var a=this._internalArray.slice(0),b=0;b0&&this.animate()},Object.defineProperty(a.prototype,"x",{get:function(){return null!==this._x&&void 0!==this._x||(this.axis%2===0?this.align%2===0?this._x=this.dom.offsetLeft:this._x=this.dom.offsetLeft+this.width:this.align%2===0?this._x=this.parent.width-this.dom.offsetLeft:this._x=this.parent.width-this.dom.offsetLeft-this.width),this.absolute?this._x:this._x/this.parent.width},set:function(a){this._x=a,this.absolute||(this._x*=this.parent.width),this.axis%2===0?this.dom.style.left=this._x+(this.align%2===0?0:-this.width)+"px":this.dom.style.right=this._x+(this.align%2===0?-this.width:0)+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"y",{get:function(){return null!==this._y&&void 0!==this._y||(this.axis<2?this.align<2?this._y=this.dom.offsetTop:this._y=this.dom.offsetTop+this.height:this.align<2?this._y=this.parent.height-this.dom.offsetTop:this._y=this.parent.height-this.dom.offsetTop-this.height),this.absolute?this._y:this._y/this.parent.height},set:function(a){this._y=a,this.absolute||(this._y*=this.parent.height),this.axis<2?this.dom.style.top=this._y+(this.align<2?0:-this.height)+"px":this.dom.style.bottom=this._y+(this.align<2?-this.height:0)+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"bottom",{get:function(){var a=Math.floor(this.axis/2)===Math.floor(this.align/2);return this.y+(a?this.height:0)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"right",{get:function(){var a=this.axis%2===this.align%2;return this.x+(a?this.width:0)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"width",{get:function(){return null!==this._width&&void 0!==this._width||(this._width=this.dom.offsetWidth),this._width},set:function(a){this._width=a,this.dom.style.width=this._width+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"height",{get:function(){return null!==this._height&&void 0!==this._height||(this._height=this.dom.offsetHeight),this._height},set:function(a){this._height=a,this.dom.style.height=this._height+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"size",{get:function(){return this._size},set:function(a){this._size=a,this.dom.style.fontSize=this._size+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"color",{get:function(){return this._color},set:function(a){this._color=a;var b=a.toString(16);b=b.length>=6?b:new Array(6-b.length+1).join("0")+b,this.dom.style.color="#"+b,0===this._color&&(this.dom.className=this.parent.options.global.className+" rshadow")},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"alpha",{get:function(){return this._alpha},set:function(a){this._alpha=a,this.dom.style.opacity=Math.min(this._alpha,this.parent.options.global.opacity)+""},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"border",{get:function(){return this._border},set:function(a){this._border=a,this._border?this.dom.style.border="1px solid #00ffff":this.dom.style.border="none"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"shadow",{get:function(){return this._shadow},set:function(a){this._shadow=a,this._shadow||(this.dom.className=this.parent.options.global.className+" noshadow")},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"font",{get:function(){return this._font},set:function(a){this._font=a,this._font.length>0?this.dom.style.fontFamily=this._font:this.dom.style.fontFamily=""},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"transform",{get:function(){return this._transform.flatArray},set:function(a){this._transform=new CommentUtils.Matrix3D(a),null!==this.dom&&(this.dom.style.transform=this._transform.toCss())},enumerable:!0,configurable:!0}),a.prototype.time=function(a){this.ttl-=a,this.ttl<0&&(this.ttl=0),this.movable&&this.update(),this.ttl<=0&&this.finish()},a.prototype.update=function(){this.animate()},a.prototype.invalidate=function(){this._x=null,this._y=null,this._width=null,this._height=null},a.prototype._execMotion=function(a,b){for(var c in a)if(a.hasOwnProperty(c)){var d=a[c];this[c]=d.easing(Math.min(Math.max(b-d.delay,0),d.dur),d.from,d.to-d.from,d.dur)}},a.prototype.animate=function(){if(this._alphaMotion&&(this.alpha=(this.dur-this.ttl)*(this._alphaMotion.to-this._alphaMotion.from)/this.dur+this._alphaMotion.from),0!==this.motion.length){var a=Math.max(this.ttl,0),b=this.dur-a-this._motionStart[this._curMotion];return this._execMotion(this.motion[this._curMotion],b),this.dur-a>this._motionEnd[this._curMotion]?(this._curMotion++,void(this._curMotion>=this.motion.length&&(this._curMotion=this.motion.length-1))):void 0}},a.prototype.finish=function(){this.parent.finish(this)},a.prototype.toString=function(){return["[",this.stime,"|",this.ttl,"/",this.dur,"]","(",this.mode,")",this.text].join("")},a.LINEAR=function(a,b,c,d){return a*c/d+b},a}(),ScrollComment=function(a){function b(b,c){a.call(this,b,c),this.dur*=this.parent.options.scroll.scale,this.ttl*=this.parent.options.scroll.scale}return __extends(b,a),Object.defineProperty(b.prototype,"alpha",{set:function(a){this._alpha=a,this.dom.style.opacity=Math.min(Math.min(this._alpha,this.parent.options.global.opacity),this.parent.options.scroll.opacity)+""},enumerable:!0,configurable:!0}),b.prototype.init=function(b){void 0===b&&(b=null),a.prototype.init.call(this,b),this.x=this.parent.width,this.parent.options.scroll.opacity<1&&(this.alpha=this._alpha),this.absolute=!0},b.prototype.update=function(){this.x=this.ttl/this.dur*(this.parent.width+this.width)-this.width},b}(CoreComment),CommentFactory=function(){function a(){this._bindings={}}return a._simpleScrollingInitializer=function(a,b){var c=new ScrollComment(a,b);switch(c.mode){case 1:c.align=0,c.axis=0;break;case 2:c.align=2,c.axis=2;break;case 6:c.align=1,c.axis=1}return c.init(),a.stage.appendChild(c.dom),c},a._simpleAnchoredInitializer=function(a,b){var c=new CoreComment(a,b);switch(c.mode){case 4:c.align=2,c.axis=2;break;case 5:c.align=0,c.axis=0}return c.init(),a.stage.appendChild(c.dom),c},a._advancedCoreInitializer=function(a,b){var c=new CoreComment(a,b);return c.init(),c.transform=CommentUtils.Matrix3D.createRotationMatrix(0,b.rY,b.rZ).flatArray,a.stage.appendChild(c.dom),c},a.defaultFactory=function(){var b=new a;return b.bind(1,a._simpleScrollingInitializer),b.bind(2,a._simpleScrollingInitializer),b.bind(6,a._simpleScrollingInitializer),b.bind(4,a._simpleAnchoredInitializer),b.bind(5,a._simpleAnchoredInitializer),b.bind(7,a._advancedCoreInitializer),b.bind(17,a._advancedCoreInitializer),b},a.prototype.bind=function(a,b){this._bindings[a]=b},a.prototype.create=function(a,b){if(null===b||!b.hasOwnProperty("mode"))throw new Error("Comment format incorrect");if(!this._bindings.hasOwnProperty(b.mode))throw new Error("No binding for comment type "+b.mode);return this._bindings[b.mode](a,b)},a}(),__extends=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},CommentSpaceAllocator=function(){function a(a,b){void 0===a&&(a=0),void 0===b&&(b=0),this._pools=[[]],this.avoid=1,this._width=a,this._height=b}return a.prototype.willCollide=function(a,b){return a.stime+a.ttl>=b.stime+b.ttl/2},a.prototype.pathCheck=function(a,b,c){for(var d=a+b.height,e=b.right,f=0;fd||c[f].bottome))return!1;if(this.willCollide(c[f],b))return!1}return!0},a.prototype.assign=function(a,b){for(;this._pools.length<=b;)this._pools.push([]);var c=this._pools[b];if(0===c.length)return a.cindex=b,0;if(this.pathCheck(0,a,c))return a.cindex=b,0;for(var d=0,e=0;ethis._height));e++)if(this.pathCheck(d,a,c))return a.cindex=b,d;return this.assign(a,b+1)},a.prototype.add=function(a){a.height>this._height?(a.cindex=-2,a.y=0):(a.y=this.assign(a,0),BinArray.binsert(this._pools[a.cindex],a,function(a,b){return a.bottomb.bottom?1:0}))},a.prototype.remove=function(a){if(!(a.cindex<0)){if(a.cindex>=this._pools.length)throw new Error("cindex out of bounds");var b=this._pools[a.cindex].indexOf(a);b<0||this._pools[a.cindex].splice(b,1)}},a.prototype.setBounds=function(a,b){this._width=a,this._height=b},a}(),AnchorCommentSpaceAllocator=function(a){function b(){a.apply(this,arguments)}return __extends(b,a),b.prototype.add=function(b){a.prototype.add.call(this,b),b.x=(this._width-b.width)/2},b.prototype.willCollide=function(a,b){return!0},b.prototype.pathCheck=function(a,b,c){for(var d=a+b.height,e=0;ed||c[e].bottom0)){var a=(new Date).getTime(),c=this;b=window.setInterval(function(){var b=(new Date).getTime()-a;a=(new Date).getTime(),c.onTimerEvent(b,c)},10)}},this.stopTimer=function(){window.clearInterval(b),b=0}}var b=function(a,b){return a.stime>b.stime?2:a.stimeb.date?1:a.dateb.dbid?1:a.dbidb.stime?1:0})},a.prototype.validate=function(a){return null!=a&&this.filter.doValidate(a)},a.prototype.load=function(a){this.timeline=a,this.timeline.sort(b),this.dispatchEvent("load")},a.prototype.insert=function(a){var c=BinArray.binsert(this.timeline,a,b);c<=this.position&&this.position++,this.dispatchEvent("insert")},a.prototype.clear=function(){for(;this.runline.length>0;)this.runline[0].finish();this.dispatchEvent("clear")},a.prototype.setBounds=function(){this.width=this.stage.offsetWidth,this.height=this.stage.offsetHeight,this.dispatchEvent("resize");for(var a in this.csa)this.csa[a].setBounds(this.width,this.height);this.stage.style.perspective=this.width*Math.tan(40*Math.PI/180)/2+"px",this.stage.style.webkitPerspective=this.width*Math.tan(40*Math.PI/180)/2+"px"},a.prototype.init=function(){this.setBounds(),null==this.filter&&(this.filter=new CommentFilter),null==this.factory&&(this.factory=CommentFactory.defaultFactory())},a.prototype.time=function(a){if(a-=1,this.position>=this.timeline.length||Math.abs(this._lastPosition-a)>=2e3){if(this.seek(a),this._lastPosition=a,this.timeline.length<=this.position)return}else this._lastPosition=a;for(;this.position0&&this.runline.length>this.limiter||this.validate(this.timeline[this.position])&&this.send(this.timeline[this.position])},a.prototype.rescale=function(){},a.prototype.send=function(a){if(8===a.mode)return console.log(a),void(this.scripting&&console.log(this.scripting.eval(a.code)));if(null==this.filter||(a=this.filter.doModify(a),null!=a)){var b=this.factory.create(this,a);switch(b.mode){default:case 1:this.csa.scroll.add(b);break;case 2:this.csa.scrollbtm.add(b);break;case 4:this.csa.bottom.add(b);break;case 5:this.csa.top.add(b);break;case 6:this.csa.reverse.add(b);break;case 7:case 17:}b.y=b.y,this.dispatchEvent("enterComment",b),this.runline.push(b)}},a.prototype.finish=function(a){this.dispatchEvent("exitComment",a),this.stage.removeChild(a.dom);var b=this.runline.indexOf(a);switch(b>=0&&this.runline.splice(b,1),a.mode){default:case 1:this.csa.scroll.remove(a);break;case 2:this.csa.scrollbtm.remove(a);break;case 4:this.csa.bottom.remove(a);break;case 5:this.csa.top.remove(a);break;case 6:this.csa.reverse.remove(a);break;case 7:}},a.prototype.addEventListener=function(a,b){"undefined"!=typeof this._listeners[a]?this._listeners[a].push(b):this._listeners[a]=[b]},a.prototype.dispatchEvent=function(a,b){if("undefined"!=typeof this._listeners[a])for(var c=0;c=200&&this.status<300?f(this.response):g(new Error(this.status+" "+this.statusText))},h.onerror=function(){g(new Error(this.status+" "+this.statusText))},h.open(a,i),"undefined"!=typeof e?h.send(e):h.send()})},a.JSONProvider=function(b,c,d,e){return a.BaseHttpProvider(b,c,"json",d,e).then(function(a){return a})},a.XMLProvider=function(b,c,d,e){return a.BaseHttpProvider(b,c,"document",d,e).then(function(a){return a})},a.TextProvider=function(b,c,d,e){return a.BaseHttpProvider(b,c,"text",d,e).then(function(a){return a})},a.prototype.addStaticSource=function(a,b){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more sources.");return b in this._staticSources||(this._staticSources[b]=[]),this._staticSources[b].push(a),this},a.prototype.addDynamicSource=function(a,b){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more sources.");return b in this._dynamicSources||(this._dynamicSources[b]=[]),this._dynamicSources[b].push(a),this},a.prototype.addTarget=function(a){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more targets.");if(!(a instanceof CommentManager))throw new Error("Expected the target to be an instance of CommentManager.");return this._targets.push(a),this},a.prototype.addParser=function(a,b){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more parsers.");return b in this._parsers||(this._parsers[b]=[]),this._parsers[b].unshift(a),this},a.prototype.applyParsersOne=function(a,b){return new Promise(function(c,d){if(!(b in this._parsers))return void d(new Error('No parsers defined for "'+b+'"'));for(var e=0;e=7&&(f.rZ=parseInt(g[5],10),f.rY=parseInt(g[6],10)),f.motion=[],f.movable=!1,g.length>=11){f.movable=!0;var h=500,i={x:{from:f.x,to:parseFloat(g[7]),dur:h,delay:0},y:{from:f.y,to:parseFloat(g[8]),dur:h,delay:0}};if(""!==g[9]&&(h=parseInt(g[9],10),i.x.dur=h,i.y.dur=h),""!==g[10]&&(i.x.delay=parseInt(g[10],10),i.y.delay=parseInt(g[10],10)),g.length>11&&(f.shadow="false"!==g[11],null!=g[12]&&(f.font=g[12]),g.length>14)){"relative"===f.position&&(this._logBadComments&&console.warn("Cannot mix relative and absolute positioning!"),f.position="absolute");for(var j=g[14],k={x:i.x.from,y:i.y.from},l=[],m=new RegExp("([a-zA-Z])\\s*(\\d+)[, ](\\d+)","g"),n=j.split(/[a-zA-Z]/).length-1,o=m.exec(j);null!==o;){switch(o[1]){case"M":k.x=parseInt(o[2],10),k.y=parseInt(o[3],10);break;case"L":l.push({x:{from:k.x,to:parseInt(o[2],10),dur:h/n,delay:0},y:{from:k.y,to:parseInt(o[3],10),dur:h/n,delay:0}}),k.x=parseInt(o[2],10),k.y=parseInt(o[3],10)}o=m.exec(j)}i=null,f.motion=l}null!==i&&f.motion.push(i)}f.dur=2500,g[3]<12&&(f.dur=1e3*g[3]);var p=g[2].split("-");if(null!=p&&p.length>1){var q=parseFloat(p[0]),r=parseFloat(p[1]);f.opacity=q,q!==r&&(f.alpha={from:q,to:r})}}catch(a){this._logBadComments&&(console.warn("Error occurred in JSON parsing. Could not parse comment."),console.log("[DEBUG] "+e))}else 8===f.mode?f.code=e:this._logBadComments&&(console.warn("Unknown comment type : "+f.mode+". Not doing further parsing."),console.log("[DEBUG] "+e));return null!==f.text&&"string"==typeof f.text&&(f.text=f.text.replace(/\u25a0/g,"█")),f},a.XMLParser.prototype.parseMany=function(a){var b=[];try{b=a.getElementsByTagName("d")}catch(a){return null}for(var c=[],d=0;d=6){if(b.stime=1e3*parseFloat(c[0]),b.color=parseInt(c[1]),b.mode=parseInt(c[2]),b.size=parseInt(c[3]),b.hash=c[4],b.date=parseInt(c[5]),b.position="absolute",7!==b.mode)b.text=a.m.replace(/(\/n|\\n|\n|\r\n|\\r)/g,"\n"),b.text=b.text.replace(/\r/g,"\n"),b.text=b.text.replace(/\s/g," ");else{try{var d=JSON.parse(a.m)}catch(a){return this._logBadComments&&(console.warn("Error parsing internal data for comment"),console.log("[Dbg] "+b.text)),null}if(b.position="relative",b.text=d.n,b.text=b.text.replace(/\ /g," "),"number"==typeof d.a?b.opacity=d.a:b.opacity=1,"object"==typeof d.p?(b.x=d.p.x/1e3,b.y=d.p.y/1e3):(b.x=0,b.y=0),"number"==typeof d.c)switch(d.c){case 0:b.align=0;break;case 2:b.align=1;break;case 6:b.align=2;break;case 8:b.align=3;break;default:this._logNotImplemented&&console.log("Cannot handle aligning to center! AlignMode="+d.c)}if(b.axis=0,b.shadow=d.b,b.dur=4e3,"number"==typeof d.l&&(b.dur=1e3*d.l),null!=d.z&&d.z.length>0){b.movable=!0,b.motion=[];for(var e=0,f={x:b.x,y:b.y,alpha:b.opacity,color:b.color},g=0;g0&&this._logNotImplemented&&console.log("[Dbg] Filters not supported! "+JSON.stringify(d.w.l))),null!=d.r&&null!=d.k&&(b.rX=d.r,b.rY=d.k)}return b}return this._logBadComments&&(console.warn("Dropping this comment due to insufficient parameters. Got: "+c.length),console.log("[Dbg] "+a.c)),null},a.JSONParser.prototype.parseMany=function(a){if(!Array.isArray(a))return null;for(var b=[],c=0;c=0)return a.length;for(var d=0,e=0,f=0,g=a.length-1;d<=g;){if(e=Math.floor((g+d+1)/2),f++,c(b,a[e-1])>=0&&c(b,a[e])<0)return e;if(c(b,a[e-1])<0)g=e-1;else{if(!(c(b,a[e])>=0))throw new Error("Program Error. Inconsistent comparator or unsorted array!");d=e}if(f>1500)throw new Error("Iteration depth exceeded. Inconsistent comparator or astronomical dataset!")}return-1},a.binsert=function(b,c,d){var e=a.bsearch(b,c,d);return b.splice(e,0,c),e},a}(),CommentUtils;!function(a){var b=function(){function a(a){if(this._internalArray=null,!Array.isArray(a))throw new Error("Not an array. Cannot construct matrix.");if(16!=a.length)throw new Error("Illegal Dimensions. Matrix3D should be 4x4 matrix.");this._internalArray=a}return Object.defineProperty(a.prototype,"flatArray",{get:function(){return this._internalArray.slice(0)},set:function(a){throw new Error("Not permitted. Matrices are immutable.")},enumerable:!0,configurable:!0}),a.prototype.isIdentity=function(){return this.equals(a.identity())},a.prototype.dot=function(b){for(var c=this._internalArray.slice(0),d=b._internalArray.slice(0),e=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],f=0;f<4;f++)for(var g=0;g<4;g++)for(var h=0;h<4;h++)e[4*f+g]+=c[4*f+h]*d[4*h+g];return new a(e)},a.prototype.equals=function(a){for(var b=0;b<16;b++)if(this._internalArray[b]!==a._internalArray[b])return!1;return!0},a.prototype.toCss=function(){for(var a=this._internalArray.slice(0),b=0;b0&&this.animate()},Object.defineProperty(a.prototype,"x",{get:function(){return null!==this._x&&void 0!==this._x||(this.axis%2===0?this.align%2===0?this._x=this.dom.offsetLeft:this._x=this.dom.offsetLeft+this.width:this.align%2===0?this._x=this.parent.width-this.dom.offsetLeft:this._x=this.parent.width-this.dom.offsetLeft-this.width),this.absolute?this._x:this._x/this.parent.width},set:function(a){this._x=a,this.absolute||(this._x*=this.parent.width),this.axis%2===0?this.dom.style.left=this._x+(this.align%2===0?0:-this.width)+"px":this.dom.style.right=this._x+(this.align%2===0?-this.width:0)+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"y",{get:function(){return null!==this._y&&void 0!==this._y||(this.axis<2?this.align<2?this._y=this.dom.offsetTop:this._y=this.dom.offsetTop+this.height:this.align<2?this._y=this.parent.height-this.dom.offsetTop:this._y=this.parent.height-this.dom.offsetTop-this.height),this.absolute?this._y:this._y/this.parent.height},set:function(a){this._y=a,this.absolute||(this._y*=this.parent.height),this.axis<2?this.dom.style.top=this._y+(this.align<2?0:-this.height)+"px":this.dom.style.bottom=this._y+(this.align<2?-this.height:0)+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"bottom",{get:function(){var a=Math.floor(this.axis/2)===Math.floor(this.align/2);return this.y+(a?this.height:0)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"right",{get:function(){var a=this.axis%2===this.align%2;return this.x+(a?this.width:0)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"width",{get:function(){return null!==this._width&&void 0!==this._width||(this._width=this.dom.offsetWidth),this._width},set:function(a){this._width=a,this.dom.style.width=this._width+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"height",{get:function(){return null!==this._height&&void 0!==this._height||(this._height=this.dom.offsetHeight),this._height},set:function(a){this._height=a,this.dom.style.height=this._height+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"size",{get:function(){return this._size},set:function(a){this._size=a,this.dom.style.fontSize=this._size+"px"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"color",{get:function(){return this._color},set:function(a){this._color=a;var b=a.toString(16);b=b.length>=6?b:new Array(6-b.length+1).join("0")+b,this.dom.style.color="#"+b,0===this._color&&(this.dom.className=this.parent.options.global.className+" rshadow")},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"alpha",{get:function(){return this._alpha},set:function(a){this._alpha=a,this.dom.style.opacity=Math.min(this._alpha,this.parent.options.global.opacity)+""},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"border",{get:function(){return this._border},set:function(a){this._border=a,this._border?this.dom.style.border="1px solid #00ffff":this.dom.style.border="none"},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"shadow",{get:function(){return this._shadow},set:function(a){this._shadow=a,this._shadow||(this.dom.className=this.parent.options.global.className+" noshadow")},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"font",{get:function(){return this._font},set:function(a){this._font=a,this._font.length>0?this.dom.style.fontFamily=this._font:this.dom.style.fontFamily=""},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"transform",{get:function(){return this._transform.flatArray},set:function(a){this._transform=new CommentUtils.Matrix3D(a),null!==this.dom&&(this.dom.style.transform=this._transform.toCss())},enumerable:!0,configurable:!0}),a.prototype.time=function(a){this.ttl-=a,this.ttl<0&&(this.ttl=0),this.movable&&this.update(),this.ttl<=0&&this.finish()},a.prototype.update=function(){this.animate()},a.prototype.invalidate=function(){this._x=null,this._y=null,this._width=null,this._height=null},a.prototype._execMotion=function(a,b){for(var c in a)if(a.hasOwnProperty(c)){var d=a[c];this[c]=d.easing(Math.min(Math.max(b-d.delay,0),d.dur),d.from,d.to-d.from,d.dur)}},a.prototype.animate=function(){if(this._alphaMotion&&(this.alpha=(this.dur-this.ttl)*(this._alphaMotion.to-this._alphaMotion.from)/this.dur+this._alphaMotion.from),0!==this.motion.length){var a=Math.max(this.ttl,0),b=this.dur-a-this._motionStart[this._curMotion];return this._execMotion(this.motion[this._curMotion],b),this.dur-a>this._motionEnd[this._curMotion]?(this._curMotion++,void(this._curMotion>=this.motion.length&&(this._curMotion=this.motion.length-1))):void 0}},a.prototype.finish=function(){this.parent.finish(this)},a.prototype.toString=function(){return["[",this.stime,"|",this.ttl,"/",this.dur,"]","(",this.mode,")",this.text].join("")},a.LINEAR=function(a,b,c,d){return a*c/d+b},a}(),ScrollComment=function(a){function b(b,c){a.call(this,b,c),this.dur*=this.parent.options.scroll.scale,this.ttl*=this.parent.options.scroll.scale}return __extends(b,a),Object.defineProperty(b.prototype,"alpha",{set:function(a){this._alpha=a,this.dom.style.opacity=Math.min(Math.min(this._alpha,this.parent.options.global.opacity),this.parent.options.scroll.opacity)+""},enumerable:!0,configurable:!0}),b.prototype.init=function(b){void 0===b&&(b=null),a.prototype.init.call(this,b),this.x=this.parent.width,this.parent.options.scroll.opacity<1&&(this.alpha=this._alpha),this.absolute=!0},b.prototype.update=function(){this.x=this.ttl/this.dur*(this.parent.width+this.width)-this.width},b}(CoreComment),CommentFactory=function(){function a(){this._bindings={}}return a._simpleScrollingInitializer=function(a,b){var c=new ScrollComment(a,b);switch(c.mode){case 1:c.align=0,c.axis=0;break;case 2:c.align=2,c.axis=2;break;case 6:c.align=1,c.axis=1}return c.init(),a.stage.appendChild(c.dom),c},a._simpleAnchoredInitializer=function(a,b){var c=new CoreComment(a,b);switch(c.mode){case 4:c.align=2,c.axis=2;break;case 5:c.align=0,c.axis=0}return c.init(),a.stage.appendChild(c.dom),c},a._advancedCoreInitializer=function(a,b){var c=new CoreComment(a,b);return c.init(),c.transform=CommentUtils.Matrix3D.createRotationMatrix(0,b.rY,b.rZ).flatArray,a.stage.appendChild(c.dom),c},a.defaultFactory=function(){var b=new a;return b.bind(1,a._simpleScrollingInitializer),b.bind(2,a._simpleScrollingInitializer),b.bind(6,a._simpleScrollingInitializer),b.bind(4,a._simpleAnchoredInitializer),b.bind(5,a._simpleAnchoredInitializer),b.bind(7,a._advancedCoreInitializer),b.bind(17,a._advancedCoreInitializer),b},a.prototype.bind=function(a,b){this._bindings[a]=b},a.prototype.create=function(a,b){if(null===b||!b.hasOwnProperty("mode"))throw new Error("Comment format incorrect");if(!this._bindings.hasOwnProperty(b.mode))throw new Error("No binding for comment type "+b.mode);return this._bindings[b.mode](a,b)},a}(),__extends=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},CommentSpaceAllocator=function(){function a(a,b){void 0===a&&(a=0),void 0===b&&(b=0),this._pools=[[]],this.avoid=1,this._width=a,this._height=b}return a.prototype.willCollide=function(a,b){return a.stime+a.ttl>=b.stime+b.ttl/2},a.prototype.pathCheck=function(a,b,c){for(var d=a+b.height,e=b.right,f=0;fd||c[f].bottome))return!1;if(this.willCollide(c[f],b))return!1}return!0},a.prototype.assign=function(a,b){for(;this._pools.length<=b;)this._pools.push([]);var c=this._pools[b];if(0===c.length)return a.cindex=b,0;if(this.pathCheck(0,a,c))return a.cindex=b,0;for(var d=0,e=0;ethis._height));e++)if(this.pathCheck(d,a,c))return a.cindex=b,d;return this.assign(a,b+1)},a.prototype.add=function(a){a.height>this._height?(a.cindex=-2,a.y=0):(a.y=this.assign(a,0),BinArray.binsert(this._pools[a.cindex],a,function(a,b){return a.bottomb.bottom?1:0}))},a.prototype.remove=function(a){if(!(a.cindex<0)){if(a.cindex>=this._pools.length)throw new Error("cindex out of bounds");var b=this._pools[a.cindex].indexOf(a);b<0||this._pools[a.cindex].splice(b,1)}},a.prototype.setBounds=function(a,b){this._width=a,this._height=b},a}(),AnchorCommentSpaceAllocator=function(a){function b(){a.apply(this,arguments)}return __extends(b,a),b.prototype.add=function(b){a.prototype.add.call(this,b),b.x=(this._width-b.width)/2},b.prototype.willCollide=function(a,b){return!0},b.prototype.pathCheck=function(a,b,c){for(var d=a+b.height,e=0;ed||c[e].bottom0)){var a=(new Date).getTime(),c=this;b=window.setInterval(function(){var b=(new Date).getTime()-a;a=(new Date).getTime(),c.onTimerEvent(b,c)},10)}},this.stopTimer=function(){window.clearInterval(b),b=0}}var b=function(a,b){return a.stime>b.stime?2:a.stimeb.date?1:a.dateb.dbid?1:a.dbidb.stime?1:0})},a.prototype.validate=function(a){return null!=a&&this.filter.doValidate(a)},a.prototype.load=function(a){this.timeline=a,this.timeline.sort(b),this.dispatchEvent("load")},a.prototype.insert=function(a){var c=BinArray.binsert(this.timeline,a,b);c<=this.position&&this.position++,this.dispatchEvent("insert")},a.prototype.clear=function(){for(;this.runline.length>0;)this.runline[0].finish();this.dispatchEvent("clear")},a.prototype.setBounds=function(){this.width=this.stage.offsetWidth,this.height=this.stage.offsetHeight,this.dispatchEvent("resize");for(var a in this.csa)this.csa[a].setBounds(this.width,this.height);this.stage.style.perspective=this.width*Math.tan(40*Math.PI/180)/2+"px",this.stage.style.webkitPerspective=this.width*Math.tan(40*Math.PI/180)/2+"px"},a.prototype.init=function(){this.setBounds(),null==this.filter&&(this.filter=new CommentFilter),null==this.factory&&(this.factory=CommentFactory.defaultFactory())},a.prototype.time=function(a){if(a-=1,this.position>=this.timeline.length||Math.abs(this._lastPosition-a)>=2e3){if(this.seek(a),this._lastPosition=a,this.timeline.length<=this.position)return}else this._lastPosition=a;for(;this.position0&&this.runline.length>this.limiter||this.validate(this.timeline[this.position])&&this.send(this.timeline[this.position])},a.prototype.rescale=function(){},a.prototype.send=function(a){if(8===a.mode)return console.log(a),void(this.scripting&&console.log(this.scripting.eval(a.code)));if(null==this.filter||(a=this.filter.doModify(a),null!=a)){var b=this.factory.create(this,a);switch(b.mode){default:case 1:this.csa.scroll.add(b);break;case 2:this.csa.scrollbtm.add(b);break;case 4:this.csa.bottom.add(b);break;case 5:this.csa.top.add(b);break;case 6:this.csa.reverse.add(b);break;case 7:case 17:}b.y=b.y,this.dispatchEvent("enterComment",b),this.runline.push(b)}},a.prototype.finish=function(a){this.dispatchEvent("exitComment",a),this.stage.removeChild(a.dom);var b=this.runline.indexOf(a);switch(b>=0&&this.runline.splice(b,1),a.mode){default:case 1:this.csa.scroll.remove(a);break;case 2:this.csa.scrollbtm.remove(a);break;case 4:this.csa.bottom.remove(a);break;case 5:this.csa.top.remove(a);break;case 6:this.csa.reverse.remove(a);break;case 7:}},a.prototype.addEventListener=function(a,b){"undefined"!=typeof this._listeners[a]?this._listeners[a].push(b):this._listeners[a]=[b]},a.prototype.dispatchEvent=function(a,b){if("undefined"!=typeof this._listeners[a])for(var c=0;c0;){var f=d.shift();if(""!==f&&(e.hasOwnProperty(f)&&(e=e[f]),null===e||"undefined"==typeof e)){e=null;break}}if(null===e)return!0;switch(b.op){case"~":case"regexp":return new RegExp(b.value).test(e.toString());case"=":case"eq":return b.value===e.toString();case"NOT":return!a(b.value,c);case"AND":return!!Array.isArray(b.value)&&b.value.every(function(b){return a(b,c)});case"OR":return!!Array.isArray(b.value)&&b.value.some(function(b){return a(b,c)});default:return!1}}function b(){this.rules=[],this.modifiers=[],this.allowUnknownTypes=!0,this.allowTypes={1:!0,2:!0,4:!0,5:!0,6:!0,7:!0,8:!0,17:!0}}b.prototype.doModify=function(a){for(var b=0;b=200&&this.status<300?f(this.response):g(new Error(this.status+" "+this.statusText))},h.onerror=function(){g(new Error(this.status+" "+this.statusText))},h.open(a,i),"undefined"!=typeof e?h.send(e):h.send()})},a.JSONProvider=function(b,c,d,e){return a.BaseHttpProvider(b,c,"json",d,e).then(function(a){return a})},a.XMLProvider=function(b,c,d,e){return a.BaseHttpProvider(b,c,"document",d,e).then(function(a){return a})},a.TextProvider=function(b,c,d,e){return a.BaseHttpProvider(b,c,"text",d,e).then(function(a){return a})},a.prototype.addStaticSource=function(a,b){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more sources.");return b in this._staticSources||(this._staticSources[b]=[]),this._staticSources[b].push(a),this},a.prototype.addDynamicSource=function(a,b){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more sources.");return b in this._dynamicSources||(this._dynamicSources[b]=[]),this._dynamicSources[b].push(a),this},a.prototype.addTarget=function(a){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more targets.");if(!(a instanceof CommentManager))throw new Error("Expected the target to be an instance of CommentManager.");return this._targets.push(a),this},a.prototype.addParser=function(a,b){if(this._destroyed)throw new Error("Comment provider has been destroyed, cannot attach more parsers.");return b in this._parsers||(this._parsers[b]=[]),this._parsers[b].unshift(a),this},a.prototype.applyParsersOne=function(a,b){return new Promise(function(c,d){if(!(b in this._parsers))return void d(new Error('No parsers defined for "'+b+'"'));for(var e=0;e=7&&(f.rZ=parseInt(g[5],10),f.rY=parseInt(g[6],10)),f.motion=[],f.movable=!1,g.length>=11){f.movable=!0;var h=500,i={x:{from:f.x,to:parseFloat(g[7]),dur:h,delay:0},y:{from:f.y,to:parseFloat(g[8]),dur:h,delay:0}};if(""!==g[9]&&(h=parseInt(g[9],10),i.x.dur=h,i.y.dur=h),""!==g[10]&&(i.x.delay=parseInt(g[10],10),i.y.delay=parseInt(g[10],10)),g.length>11&&(f.shadow="false"!==g[11],null!=g[12]&&(f.font=g[12]),g.length>14)){"relative"===f.position&&(this._logBadComments&&console.warn("Cannot mix relative and absolute positioning!"),f.position="absolute");for(var j=g[14],k={x:i.x.from,y:i.y.from},l=[],m=new RegExp("([a-zA-Z])\\s*(\\d+)[, ](\\d+)","g"),n=j.split(/[a-zA-Z]/).length-1,o=m.exec(j);null!==o;){switch(o[1]){case"M":k.x=parseInt(o[2],10),k.y=parseInt(o[3],10);break;case"L":l.push({x:{from:k.x,to:parseInt(o[2],10),dur:h/n,delay:0},y:{from:k.y,to:parseInt(o[3],10),dur:h/n,delay:0}}),k.x=parseInt(o[2],10),k.y=parseInt(o[3],10)}o=m.exec(j)}i=null,f.motion=l}null!==i&&f.motion.push(i)}f.dur=2500,g[3]<12&&(f.dur=1e3*g[3]);var p=g[2].split("-");if(null!=p&&p.length>1){var q=parseFloat(p[0]),r=parseFloat(p[1]);f.opacity=q,q!==r&&(f.alpha={from:q,to:r})}}catch(a){this._logBadComments&&(console.warn("Error occurred in JSON parsing. Could not parse comment."),console.log("[DEBUG] "+e))}else 8===f.mode?f.code=e:this._logBadComments&&(console.warn("Unknown comment type : "+f.mode+". Not doing further parsing."),console.log("[DEBUG] "+e));return null!==f.text&&"string"==typeof f.text&&(f.text=f.text.replace(/\u25a0/g,"█")),f},a.XMLParser.prototype.parseMany=function(a){var b=[];try{b=a.getElementsByTagName("d")}catch(a){return null}for(var c=[],d=0;d=6){if(b.stime=1e3*parseFloat(c[0]),b.color=parseInt(c[1]),b.mode=parseInt(c[2]),b.size=parseInt(c[3]),b.hash=c[4],b.date=parseInt(c[5]),b.position="absolute",7!==b.mode)b.text=a.m.replace(/(\/n|\\n|\n|\r\n|\\r)/g,"\n"),b.text=b.text.replace(/\r/g,"\n"),b.text=b.text.replace(/\s/g," ");else{try{var d=JSON.parse(a.m)}catch(a){return this._logBadComments&&(console.warn("Error parsing internal data for comment"),console.log("[Dbg] "+b.text)),null}if(b.position="relative",b.text=d.n,b.text=b.text.replace(/\ /g," "),"number"==typeof d.a?b.opacity=d.a:b.opacity=1,"object"==typeof d.p?(b.x=d.p.x/1e3,b.y=d.p.y/1e3):(b.x=0,b.y=0),"number"==typeof d.c)switch(d.c){case 0:b.align=0;break;case 2:b.align=1;break;case 6:b.align=2;break;case 8:b.align=3;break;default:this._logNotImplemented&&console.log("Cannot handle aligning to center! AlignMode="+d.c)}if(b.axis=0,b.shadow=d.b,b.dur=4e3,"number"==typeof d.l&&(b.dur=1e3*d.l),null!=d.z&&d.z.length>0){b.movable=!0,b.motion=[];for(var e=0,f={x:b.x,y:b.y,alpha:b.opacity,color:b.color},g=0;g0&&this._logNotImplemented&&console.log("[Dbg] Filters not supported! "+JSON.stringify(d.w.l))),null!=d.r&&null!=d.k&&(b.rX=d.r,b.rY=d.k)}return b}return this._logBadComments&&(console.warn("Dropping this comment due to insufficient parameters. Got: "+c.length),console.log("[Dbg] "+a.c)),null},a.JSONParser.prototype.parseMany=function(a){if(!Array.isArray(a))return null;for(var b=[],c=0;c 0) { + var item = path.shift(); + if (item === '') { + continue; + } + if (extracted.hasOwnProperty(item)) { + extracted = extracted[item]; + } + if (extracted === null || typeof extracted === 'undefined') { + extracted = null; + break; + } + } + if (extracted === null) { + // Null precondition implies anything + return true; + } + switch (rule.op) { + case '~': + case 'regexp': + return (new RegExp(rule.value)).test(extracted.toString()); + case '=': + case 'eq': + return rule.value === extracted.toString(); + case 'NOT': + return !_match(rule.value, cmtData); + case 'AND': + if (Array.isArray(rule.value)) { + return rule.value.every(function (r) { + return _match(r, cmtData); + }); + } else { + return false; + } + case 'OR': + if (Array.isArray(rule.value)) { + return rule.value.some(function (r) { + return _match(r, cmtData); + }); + } else { + return false; + } + default: + return false; + } + } + + function CommentFilter() { + this.rules = []; + this.modifiers = []; + this.allowUnknownTypes = true; + this.allowTypes = { + '1': true, + '2': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '17': true + }; + } + + CommentFilter.prototype.doModify = function (cmt) { + for (var k=0; k < this.modifiers.length; k++) { + cmt = this.modifiers[k](cmt); + } + return cmt; + }; + + CommentFilter.prototype.beforeSend = function (cmt) { + return cmt; + } + + CommentFilter.prototype.doValidate = function (cmtData) { + if (cmtData.mode.toString() in this.allowTypes && + !this.allowTypes[cmtData.mode.toString()]) { + return false; + } + return this.rules.every(function (rule) { + // Decide if matched + var matched = _match(rule, cmtData); + return rule.mode === 'accept' ? matched : !matched; + }); + }; + + CommentFilter.prototype.addRule = function (rule) { + if (rule.mode !== 'accept' && rule.mode !== 'reject') { + throw new Error('Rule must be of accept type or reject type.'); + } + this.rules.push(rule); + }; + + CommentFilter.prototype.addModifier = function (f) { + this.modifiers.push(f); + }; +})(); diff --git a/src/scripting/Host.js b/src/scripting/Host.js index a56a7c6..41b7584 100644 --- a/src/scripting/Host.js +++ b/src/scripting/Host.js @@ -171,8 +171,12 @@ var CCLScripting = function(workerUrl){ var WorkerHook = function(event){ try{ var resp = JSON.parse(event.data); - }catch(e){ - console.log(e); + } catch(e) { + if (e.stack) { + scripter.logger.error(e.stack); + } else { + scripter.logger.error(e); + } return; } if(resp.channel === ""){ @@ -209,8 +213,12 @@ var CCLScripting = function(workerUrl){ } break; } + case ':debug':{ + scripter.logger.log(JSON.stringify(resp.payload)); + break; + } default:{ - console.log(resp); + scripter.logger.log(JSON.stringify(resp)); break; } } diff --git a/src/scripting/Host/ScriptingContext.ts b/src/scripting/Host/ScriptingContext.ts new file mode 100644 index 0000000..bbf8228 --- /dev/null +++ b/src/scripting/Host/ScriptingContext.ts @@ -0,0 +1,61 @@ +/** + * Scripting context used by the host end of KagerouEngine + * @author Jim Chen + */ + +module Kagerou { + interface ScriptingContext { + + } + interface IDimensions { + stageWidth:number; + stageHeight:number; + screenWidth:number; + screenHeight:number; + } + + interface IBaseObject { } + interface IEnvironment { } + + class BaseScriptingContext implements ScriptingContext { + private _objects:{ [id: string] : IBaseObject; } = {}; + private stage:any; + + constructor (environment:IEnvironment, stage:any) { + + } + + public registerObject():void { + + } + + public deregisterObject():void { + + } + + public updateProperty():void { + + } + + public callMethod():void { + + } + + public getObject(id:string):IBaseObject { + + } + + public invokeError(message:string, mode:string) { + + } + + public clear():void { + + } + + public getDimensions():IDimensions { + + } + + } +} diff --git a/src/scripting/OOAPI.js b/src/scripting/OOAPI.js index df4068a..aa6b653 100644 --- a/src/scripting/OOAPI.js +++ b/src/scripting/OOAPI.js @@ -8,7 +8,7 @@ var __OOAPI = new function () { var channels = {}; function dispatchMessage (msg) { - if (channels[msg.channel]) { + if (channels.hasOwnProperty(msg.channel)) { for(var i = 0; i < channels[msg.channel].listeners.length; i++) { try { channels[msg.channel].listeners[i](msg.payload); @@ -20,6 +20,9 @@ var __OOAPI = new function () { } } } + } else { + __trace('Got message on channel "' + msg.channel + + '" but channel does not exist.', 'warn'); } }; @@ -33,10 +36,11 @@ var __OOAPI = new function () { __trace(e, 'err'); return; } - if (msg && msg.channel) { + if (msg !== null && msg.hasOwnProperty('channel') && + typeof msg.channel === 'string') { dispatchMessage(msg); } else { - _trace(msg, 'warn'); + __trace(msg, 'warn'); } }); @@ -111,7 +115,7 @@ function __channel (id, payload, callback) { 'payload': payload, 'callback': true })); - __OOAPI.addListenerChannel(id, callback, true); + __OOAPI.addListenerChannel(id, callback); }; function __schannel (id, callback) { diff --git a/src/scripting/Worker.js b/src/scripting/Worker.js index 187b5c3..725f5f4 100644 --- a/src/scripting/Worker.js +++ b/src/scripting/Worker.js @@ -2,31 +2,55 @@ var __OOAPI; importScripts("OOAPI.js"); -if(!__OOAPI){ - console.log("Error: OOAPI Not Loaded"); - self.close(); +if (!__OOAPI) { + console.log("Error: OOAPI Not Loaded"); + self.close(); }; -/** Hook independant channels, channel will not be deletable **/ +// Hook independent channels that cannot be removed __OOAPI.createChannel("::eval", 1, Math.round(Math.random() * 100000)); __OOAPI.createChannel("::debug", 1, Math.round(Math.random() * 100000)); -/** Load the BSE Abstraction Runtime **/ -importScripts('api/Runtime.js', 'api/ScriptManager.js', 'api/Player.js', 'api/Display.js', 'api/Tween.js', 'api/Utils.js','api/Global.js', 'api/Function.js'); +// Load the BSE Abstraction Runtime +importScripts('api/Runtime.js', + 'api/ScriptManager.js', + 'api/Player.js', + 'api/Display.js', + 'api/Tween.js', + 'api/Utils.js', + 'api/Global.js', + 'api/Function.js'); -/** Immediately Hook into the eval channel, blocking future hooks **/ -__schannel("::eval", function(msg){ - if(Tween && Tween.extendWithEasingFunctions){ - Tween.extendWithEasingFunctions(this); - } - var clearTimeout = Utils.clearTimeout; - var clearInterval = Utils.clearInterval; - eval(msg); +// Immediately Hook into the eval channel, blocking future hooks +__schannel("::eval", function (msg) { + // Prevent some things from being accessed in eval easily + (function (__code, importScripts, postMessage, addEventListener, self) { + if (Tween && Tween.extendWithEasingFunctions) { + Tween.extendWithEasingFunctions(this); + } + var clearTimeout = Utils.clearTimeout; + var clearInterval = Utils.clearInterval; + eval(__code); + })(msg); }); -__schannel("::debug", function(msg){ - if(msg.action === "list_channels"){ - __achannel("::worker:debug", "worker", __OOAPI.listChannels()); - } + +__schannel("::debug", function (msg) { + if (typeof msg === 'undefined' || msg === null || + !msg.hasOwnProperty('action')) { + __achannel('::worker:debug', 'worker', 'Malformed request'); + return; + } + if (msg.action === 'list-channels') { + __achannel('::worker:debug', 'worker', __OOAPI.listChannels()); + } else if (msg.action === 'raw-eval') { + try { + __achannel('::worker:debug', 'worker', eval(msg.code)); + } catch (e) { + __achannel('::worker:debug', 'worker', 'Error: ' + e); + } + } else { + __achannel('::worker:debug', 'worker', 'Unrecognized action'); + } }); __achannel("::worker:state", "worker", "running"); diff --git a/src/scripting/api/Function.js b/src/scripting/api/Function.js index 5bb2cad..1eef69e 100644 --- a/src/scripting/api/Function.js +++ b/src/scripting/api/Function.js @@ -1,56 +1,84 @@ /** These are all defined in the global namespace **/ -function trace(msg){ - __trace(msg, 'log'); +function trace (msg) { + if (typeof msg === 'object') { + __trace(JSON.stringify(msg), 'log'); + } else { + __trace(msg, 'log'); + } } -function load(library, onComplete){ - var libname = ""; - switch(library){ - default: - break; - }; - if(libname !== ""){ - try{ - require("libraries/" + libname + ".js"); - }catch(e){ - trace("Error: Import script failed."); - } - } - if(onComplete) - onComplete(); -}; - -function clone(a){ - if(null === a || "object" != typeof a) - return a; - /** Call method's own clone if possible **/ - if(a.hasOwnProperty("clone") || typeof a["clone"] === "function"){ - return a.clone(); - } - /** Perform a shallow clone */ - var b = {}; - b.constructor = a.constructor; - b.prototype = a.prototype; - for(var x in a){ - b[x] = a[x]; - } - return b; -}; - -function foreach(dtype, f){ - if(null === dtype || "object" != typeof dtype) - return; - /** DisplayObjects do not have any enumerable properties **/ - if(dtype instanceof Display.DisplayObject){ - return; - } - /** Iterates through object **/ - for(var x in dtype){ - if(dtype.hasOwnProperty(x)){ - f(x, dtype[x]); - } - } - return; -}; +function load (library, onComplete) { + if (typeof Runtime === 'undefined' || Runtime === null) { + __trace('No runtime defined. Attempting to raw-load library!', 'warn'); + importScripts(library + '.js'); + } else { + // Delegate this to runtime + Runtime.requestLibrary(library, function (error, response) { + if (error) { + __trace('Load: ' + error, 'warn'); + } else { + if (response.type === 'import') { + importScripts(response.location); + } else if (response.type === 'raw') { + try { + eval(response.code); + } catch (e) { + __trace('Load: ' + e, 'warn'); + } + } else if (response.type === 'object') { + if (typeof self === 'object' && self !== null) { + self[response.name] = response.obj; + } + } + // Execute the remaining code + if (typeof onComplete === 'function') { + onComplete(); + } + } + }); + } +} + +function clone (target) { + if (null === target || 'object' !== typeof target) { + return target; + } + + // Clone an array + if (Array.isArray(object)) { + return target.slice(0); + } + + // Call the object's own clone method if possible + if (target.hasOwnProperty('clone') || typeof target['clone'] === 'function') { + return target.clone(); + } + + // Perform a shallow clone + var copy = {}; + copy.constructor = copy.constructor; + copy.prototype = copy.prototype; + for (var x in a) { + copy[x] = target[x]; + } + return copy; +} + +function foreach (enumerable, f) { + if (null === enumerable || "object" !== typeof enumerable) { + return; + } + // DisplayObjects do not have any enumerable properties + if (enumerable instanceof Display.DisplayObject) { + return; + } + + for (var x in enumerable) { + if (enumerbale.hasOwnProperty(x)) { + f(x, enumerable[x]); + } + } + return; +} var none = null;