Merge pull request #46 from thisandagain/feature/rendering

WIP - Horizontal block rendering
This commit is contained in:
Ray Schamp 2016-02-09 12:07:57 -05:00
commit a8d3ca7df3
49 changed files with 4096 additions and 6038 deletions

View file

@ -58,8 +58,8 @@ goog.string.escapeChar=function(a){if(a in goog.string.jsEscapeCache_)return goo
goog.string.caseInsensitiveContains=function(a,b){return goog.string.contains(a.toLowerCase(),b.toLowerCase())};goog.string.countOf=function(a,b){return a&&b?a.split(b).length-1:0};goog.string.removeAt=function(a,b,c){var d=a;0<=b&&b<a.length&&0<c&&(d=a.substr(0,b)+a.substr(b+c,a.length-b-c));return d};goog.string.remove=function(a,b){var c=new RegExp(goog.string.regExpEscape(b),"");return a.replace(c,"")};
goog.string.removeAll=function(a,b){var c=new RegExp(goog.string.regExpEscape(b),"g");return a.replace(c,"")};goog.string.regExpEscape=function(a){return String(a).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")};goog.string.repeat=String.prototype.repeat?function(a,b){return a.repeat(b)}:function(a,b){return Array(b+1).join(a)};
goog.string.padNumber=function(a,b,c){a=goog.isDef(c)?a.toFixed(c):String(a);c=a.indexOf(".");-1==c&&(c=a.length);return goog.string.repeat("0",Math.max(0,b-c))+a};goog.string.makeSafe=function(a){return null==a?"":String(a)};goog.string.buildString=function(a){return Array.prototype.join.call(arguments,"")};goog.string.getRandomString=function(){return Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^goog.now()).toString(36)};
goog.string.compareVersions=function(a,b){for(var c=0,d=goog.string.trim(String(a)).split("."),e=goog.string.trim(String(b)).split("."),f=Math.max(d.length,e.length),g=0;0==c&&g<f;g++){var h=d[g]||"",k=e[g]||"",l=RegExp("(\\d*)(\\D*)","g"),q=RegExp("(\\d*)(\\D*)","g");do{var m=l.exec(h)||["","",""],p=q.exec(k)||["","",""];if(0==m[0].length&&0==p[0].length)break;var c=0==m[1].length?0:parseInt(m[1],10),n=0==p[1].length?0:parseInt(p[1],10),c=goog.string.compareElements_(c,n)||goog.string.compareElements_(0==
m[2].length,0==p[2].length)||goog.string.compareElements_(m[2],p[2])}while(0==c)}return c};goog.string.compareElements_=function(a,b){return a<b?-1:a>b?1:0};goog.string.hashCode=function(a){for(var b=0,c=0;c<a.length;++c)b=31*b+a.charCodeAt(c)>>>0;return b};goog.string.uniqueStringCounter_=2147483648*Math.random()|0;goog.string.createUniqueString=function(){return"goog_"+goog.string.uniqueStringCounter_++};
goog.string.compareVersions=function(a,b){for(var c=0,d=goog.string.trim(String(a)).split("."),e=goog.string.trim(String(b)).split("."),f=Math.max(d.length,e.length),g=0;0==c&&g<f;g++){var h=d[g]||"",k=e[g]||"",l=RegExp("(\\d*)(\\D*)","g"),m=RegExp("(\\d*)(\\D*)","g");do{var n=l.exec(h)||["","",""],q=m.exec(k)||["","",""];if(0==n[0].length&&0==q[0].length)break;var c=0==n[1].length?0:parseInt(n[1],10),p=0==q[1].length?0:parseInt(q[1],10),c=goog.string.compareElements_(c,p)||goog.string.compareElements_(0==
n[2].length,0==q[2].length)||goog.string.compareElements_(n[2],q[2])}while(0==c)}return c};goog.string.compareElements_=function(a,b){return a<b?-1:a>b?1:0};goog.string.hashCode=function(a){for(var b=0,c=0;c<a.length;++c)b=31*b+a.charCodeAt(c)>>>0;return b};goog.string.uniqueStringCounter_=2147483648*Math.random()|0;goog.string.createUniqueString=function(){return"goog_"+goog.string.uniqueStringCounter_++};
goog.string.toNumber=function(a){var b=Number(a);return 0==b&&goog.string.isEmptyOrWhitespace(a)?NaN:b};goog.string.isLowerCamelCase=function(a){return/^[a-z]+([A-Z][a-z]*)*$/.test(a)};goog.string.isUpperCamelCase=function(a){return/^([A-Z][a-z]*)+$/.test(a)};goog.string.toCamelCase=function(a){return String(a).replace(/\-([a-z])/g,function(a,c){return c.toUpperCase()})};goog.string.toSelectorCase=function(a){return String(a).replace(/([A-Z])/g,"-$1").toLowerCase()};
goog.string.toTitleCase=function(a,b){var c=goog.isString(b)?goog.string.regExpEscape(b):"\\s";return a.replace(new RegExp("(^"+(c?"|["+c+"]+":"")+")([a-z])","g"),function(a,b,c){return b+c.toUpperCase()})};goog.string.capitalize=function(a){return String(a.charAt(0)).toUpperCase()+String(a.substr(1)).toLowerCase()};goog.string.parseInt=function(a){isFinite(a)&&(a=String(a));return goog.isString(a)?/^\s*-?0x/i.test(a)?parseInt(a,16):parseInt(a,10):NaN};
goog.string.splitLimit=function(a,b,c){a=a.split(b);for(var d=[];0<c&&a.length;)d.push(a.shift()),c--;a.length&&d.push(a.join(b));return d};goog.string.editDistance=function(a,b){var c=[],d=[];if(a==b)return 0;if(!a.length||!b.length)return Math.max(a.length,b.length);for(var e=0;e<b.length+1;e++)c[e]=e;for(e=0;e<a.length;e++){d[0]=e+1;for(var f=0;f<b.length;f++)d[f+1]=Math.min(d[f]+1,c[f+1]+1,c[f]+(a[e]!=b[f]));for(f=0;f<c.length;f++)c[f]=d[f]}return d[b.length]};goog.asserts={};goog.asserts.ENABLE_ASSERTS=goog.DEBUG;goog.asserts.AssertionError=function(a,b){b.unshift(a);goog.debug.Error.call(this,goog.string.subs.apply(null,b));b.shift();this.messagePattern=a};goog.inherits(goog.asserts.AssertionError,goog.debug.Error);goog.asserts.AssertionError.prototype.name="AssertionError";goog.asserts.DEFAULT_ERROR_HANDLER=function(a){throw a;};goog.asserts.errorHandler_=goog.asserts.DEFAULT_ERROR_HANDLER;
@ -512,7 +512,7 @@ goog.ui.ControlRenderer.TOGGLE_ARIA_STATE_MAP_=goog.object.create(goog.a11y.aria
goog.a11y.aria.State.SELECTED);goog.ui.ControlRenderer.prototype.getAriaRole=function(){};goog.ui.ControlRenderer.prototype.createDom=function(a){return a.getDomHelper().createDom(goog.dom.TagName.DIV,this.getClassNames(a).join(" "),a.getContent())};goog.ui.ControlRenderer.prototype.getContentElement=function(a){return a};
goog.ui.ControlRenderer.prototype.enableClassName=function(a,b,c){if(a=a.getElement?a.getElement():a){var d=[b];goog.userAgent.IE&&!goog.userAgent.isVersionOrHigher("7")&&(d=this.getAppliedCombinedClassNames_(goog.dom.classlist.get(a),b),d.push(b));goog.dom.classlist.enableAll(a,d,c)}};goog.ui.ControlRenderer.prototype.enableExtraClassName=function(a,b,c){this.enableClassName(a,b,c)};goog.ui.ControlRenderer.prototype.canDecorate=function(a){return!0};
goog.ui.ControlRenderer.prototype.decorate=function(a,b){b.id&&a.setId(b.id);var c=this.getContentElement(b);c&&c.firstChild?a.setContentInternal(c.firstChild.nextSibling?goog.array.clone(c.childNodes):c.firstChild):a.setContentInternal(null);var d=0,e=this.getCssClass(),f=this.getStructuralCssClass(),g=!1,h=!1,k=!1,l=goog.array.toArray(goog.dom.classlist.get(b));goog.array.forEach(l,function(a){g||a!=e?h||a!=f?d|=this.getStateFromClass(a):h=!0:(g=!0,f==e&&(h=!0));this.getStateFromClass(a)==goog.ui.Component.State.DISABLED&&
(goog.asserts.assertElement(c),goog.dom.isFocusableTabIndex(c)&&goog.dom.setFocusableTabIndex(c,!1))},this);a.setStateInternal(d);g||(l.push(e),f==e&&(h=!0));h||l.push(f);var q=a.getExtraClassNames();q&&l.push.apply(l,q);if(goog.userAgent.IE&&!goog.userAgent.isVersionOrHigher("7")){var m=this.getAppliedCombinedClassNames_(l);0<m.length&&(l.push.apply(l,m),k=!0)}g&&h&&!q&&!k||goog.dom.classlist.set(b,l.join(" "));return b};
(goog.asserts.assertElement(c),goog.dom.isFocusableTabIndex(c)&&goog.dom.setFocusableTabIndex(c,!1))},this);a.setStateInternal(d);g||(l.push(e),f==e&&(h=!0));h||l.push(f);var m=a.getExtraClassNames();m&&l.push.apply(l,m);if(goog.userAgent.IE&&!goog.userAgent.isVersionOrHigher("7")){var n=this.getAppliedCombinedClassNames_(l);0<n.length&&(l.push.apply(l,n),k=!0)}g&&h&&!m&&!k||goog.dom.classlist.set(b,l.join(" "));return b};
goog.ui.ControlRenderer.prototype.initializeDom=function(a){a.isRightToLeft()&&this.setRightToLeft(a.getElement(),!0);a.isEnabled()&&this.setFocusable(a,a.isVisible())};goog.ui.ControlRenderer.prototype.setAriaRole=function(a,b){var c=b||this.getAriaRole();if(c){goog.asserts.assert(a,"The element passed as a first parameter cannot be null.");var d=goog.a11y.aria.getRole(a);c!=d&&goog.a11y.aria.setRole(a,c)}};
goog.ui.ControlRenderer.prototype.setAriaStates=function(a,b){goog.asserts.assert(a);goog.asserts.assert(b);var c=a.getAriaLabel();goog.isDefAndNotNull(c)&&this.setAriaLabel(b,c);a.isVisible()||goog.a11y.aria.setState(b,goog.a11y.aria.State.HIDDEN,!a.isVisible());a.isEnabled()||this.updateAriaState(b,goog.ui.Component.State.DISABLED,!a.isEnabled());a.isSupportedState(goog.ui.Component.State.SELECTED)&&this.updateAriaState(b,goog.ui.Component.State.SELECTED,a.isSelected());a.isSupportedState(goog.ui.Component.State.CHECKED)&&
this.updateAriaState(b,goog.ui.Component.State.CHECKED,a.isChecked());a.isSupportedState(goog.ui.Component.State.OPENED)&&this.updateAriaState(b,goog.ui.Component.State.OPENED,a.isOpen())};goog.ui.ControlRenderer.prototype.setAriaLabel=function(a,b){goog.a11y.aria.setLabel(a,b)};goog.ui.ControlRenderer.prototype.setAllowTextSelection=function(a,b){goog.style.setUnselectable(a,!b,!goog.userAgent.IE&&!goog.userAgent.OPERA)};
@ -869,8 +869,8 @@ this.anchorX_:c.viewLeft+c.viewWidth<this.anchorX_+a+this.width_+Blockly.BlockSv
Blockly.Bubble.prototype.positionBubble_=function(){this.bubbleGroup_.setAttribute("transform","translate("+(this.workspace_.RTL?this.anchorX_-this.relativeLeft_-this.width_:this.anchorX_+this.relativeLeft_)+","+(this.relativeTop_+this.anchorY_)+")")};Blockly.Bubble.prototype.getBubbleSize=function(){return{width:this.width_,height:this.height_}};
Blockly.Bubble.prototype.setBubbleSize=function(a,b){var c=2*Blockly.Bubble.BORDER_WIDTH;a=Math.max(a,c+45);b=Math.max(b,c+20);this.width_=a;this.height_=b;this.bubbleBack_.setAttribute("width",a);this.bubbleBack_.setAttribute("height",b);this.resizeGroup_&&(this.workspace_.RTL?this.resizeGroup_.setAttribute("transform","translate("+2*Blockly.Bubble.BORDER_WIDTH+","+(b-c)+") scale(-1 1)"):this.resizeGroup_.setAttribute("transform","translate("+(a-c)+","+(b-c)+")"));this.rendered_&&(this.autoLayout_&&
this.layoutBubble_(),this.positionBubble_(),this.renderArrow_());Blockly.fireUiEvent(this.bubbleGroup_,"resize")};
Blockly.Bubble.prototype.renderArrow_=function(){var a=[],b=this.width_/2,c=this.height_/2,d=-this.relativeLeft_,e=-this.relativeTop_;if(b==d&&c==e)a.push("M "+b+","+c);else{e-=c;d-=b;this.workspace_.RTL&&(d*=-1);var f=Math.sqrt(e*e+d*d),g=Math.acos(d/f);0>e&&(g=2*Math.PI-g);var h=g+Math.PI/2;h>2*Math.PI&&(h-=2*Math.PI);var k=Math.sin(h),l=Math.cos(h),q=this.getBubbleSize(),h=(q.width+q.height)/Blockly.Bubble.ARROW_THICKNESS,h=Math.min(h,q.width,q.height)/2,q=1-Blockly.Bubble.ANCHOR_RADIUS/f,d=b+
q*d,e=c+q*e,q=b+h*l,m=c+h*k,b=b-h*l,c=c-h*k,k=g+this.arrow_radians_;k>2*Math.PI&&(k-=2*Math.PI);g=Math.sin(k)*f/Blockly.Bubble.ARROW_BEND;f=Math.cos(k)*f/Blockly.Bubble.ARROW_BEND;a.push("M"+q+","+m);a.push("C"+(q+f)+","+(m+g)+" "+d+","+e+" "+d+","+e);a.push("C"+d+","+e+" "+(b+f)+","+(c+g)+" "+b+","+c)}a.push("z");this.bubbleArrow_.setAttribute("d",a.join(" "))};Blockly.Bubble.prototype.setColour=function(a){this.bubbleBack_.setAttribute("fill",a);this.bubbleArrow_.setAttribute("fill",a)};
Blockly.Bubble.prototype.renderArrow_=function(){var a=[],b=this.width_/2,c=this.height_/2,d=-this.relativeLeft_,e=-this.relativeTop_;if(b==d&&c==e)a.push("M "+b+","+c);else{e-=c;d-=b;this.workspace_.RTL&&(d*=-1);var f=Math.sqrt(e*e+d*d),g=Math.acos(d/f);0>e&&(g=2*Math.PI-g);var h=g+Math.PI/2;h>2*Math.PI&&(h-=2*Math.PI);var k=Math.sin(h),l=Math.cos(h),m=this.getBubbleSize(),h=(m.width+m.height)/Blockly.Bubble.ARROW_THICKNESS,h=Math.min(h,m.width,m.height)/2,m=1-Blockly.Bubble.ANCHOR_RADIUS/f,d=b+
m*d,e=c+m*e,m=b+h*l,n=c+h*k,b=b-h*l,c=c-h*k,k=g+this.arrow_radians_;k>2*Math.PI&&(k-=2*Math.PI);g=Math.sin(k)*f/Blockly.Bubble.ARROW_BEND;f=Math.cos(k)*f/Blockly.Bubble.ARROW_BEND;a.push("M"+m+","+n);a.push("C"+(m+f)+","+(n+g)+" "+d+","+e+" "+d+","+e);a.push("C"+d+","+e+" "+(b+f)+","+(c+g)+" "+b+","+c)}a.push("z");this.bubbleArrow_.setAttribute("d",a.join(" "))};Blockly.Bubble.prototype.setColour=function(a){this.bubbleBack_.setAttribute("fill",a);this.bubbleArrow_.setAttribute("fill",a)};
Blockly.Bubble.prototype.dispose=function(){Blockly.Bubble.unbindDragEvents_();goog.dom.removeNode(this.bubbleGroup_);this.shape_=this.content_=this.workspace_=this.resizeGroup_=this.bubbleBack_=this.bubbleArrow_=this.bubbleGroup_=null};Blockly.Icon=function(a){this.block_=a};Blockly.Icon.prototype.collapseHidden=!0;Blockly.Icon.prototype.SIZE=17;Blockly.Icon.prototype.bubble_=null;Blockly.Icon.prototype.iconX_=0;Blockly.Icon.prototype.iconY_=0;
Blockly.Icon.prototype.createIcon=function(){this.iconGroup_||(this.iconGroup_=Blockly.createSvgElement("g",{"class":"blocklyIconGroup"},null),this.drawIcon_(this.iconGroup_),this.block_.getSvgRoot().appendChild(this.iconGroup_),Blockly.bindEvent_(this.iconGroup_,"mouseup",this,this.iconClick_),this.updateEditable())};Blockly.Icon.prototype.dispose=function(){goog.dom.removeNode(this.iconGroup_);this.iconGroup_=null;this.setVisible(!1);this.block_=null};
Blockly.Icon.prototype.updateEditable=function(){this.block_.isInFlyout||!this.block_.isEditable()?Blockly.addClass_(this.iconGroup_,"blocklyIconGroupReadonly"):Blockly.removeClass_(this.iconGroup_,"blocklyIconGroupReadonly")};Blockly.Icon.prototype.isVisible=function(){return!!this.bubble_};Blockly.Icon.prototype.iconClick_=function(a){2!=Blockly.dragMode_&&(this.block_.isInFlyout||Blockly.isRightButton(a)||this.setVisible(!this.isVisible()))};
@ -885,9 +885,9 @@ this.foreignObject_.appendChild(a);Blockly.bindEvent_(this.textarea_,"mouseup",t
Blockly.Comment.prototype.resizeBubble_=function(){var a=this.bubble_.getBubbleSize(),b=2*Blockly.Bubble.BORDER_WIDTH;this.foreignObject_.setAttribute("width",a.width-b);this.foreignObject_.setAttribute("height",a.height-b);this.textarea_.style.width=a.width-b-4+"px";this.textarea_.style.height=a.height-b-4+"px"};
Blockly.Comment.prototype.setVisible=function(a){if(a!=this.isVisible())if(!this.block_.isEditable()&&!this.textarea_||goog.userAgent.IE)Blockly.Warning.prototype.setVisible.call(this,a);else{var b=this.getText(),c=this.getBubbleSize();a?(this.bubble_=new Blockly.Bubble(this.block_.workspace,this.createEditor_(),this.block_.svgPath_,this.iconX_,this.iconY_,this.width_,this.height_),this.bubble_.registerResizeEvent(this,this.resizeBubble_),this.updateColour(),this.text_=null):(this.bubble_.dispose(),
this.foreignObject_=this.textarea_=this.bubble_=null);this.setText(b);this.setBubbleSize(c.width,c.height)}};Blockly.Comment.prototype.textareaFocus_=function(a){this.bubble_.promote_();this.textarea_.focus()};Blockly.Comment.prototype.getBubbleSize=function(){return this.isVisible()?this.bubble_.getBubbleSize():{width:this.width_,height:this.height_}};Blockly.Comment.prototype.setBubbleSize=function(a,b){this.textarea_?this.bubble_.setBubbleSize(a,b):(this.width_=a,this.height_=b)};
Blockly.Comment.prototype.getText=function(){return this.textarea_?this.textarea_.value:this.text_};Blockly.Comment.prototype.setText=function(a){this.textarea_?this.textarea_.value=a:this.text_=a};Blockly.Comment.prototype.dispose=function(){this.block_.comment=null;Blockly.Icon.prototype.dispose.call(this)};Blockly.Connection=function(a,b){this.sourceBlock_=a;this.type=b;a.workspace.connectionDBList&&(this.db_=a.workspace.connectionDBList[b],this.dbOpposite_=a.workspace.connectionDBList[Blockly.OPPOSITE_TYPE[b]],this.hidden_=!this.db_)};Blockly.Connection.prototype.targetConnection=null;Blockly.Connection.prototype.check_=null;Blockly.Connection.prototype.shadowDom_=null;Blockly.Connection.prototype.x_=0;Blockly.Connection.prototype.y_=0;Blockly.Connection.prototype.inDB_=!1;
Blockly.Connection.prototype.db_=null;Blockly.Connection.prototype.dbOpposite_=null;Blockly.Connection.prototype.hidden_=null;Blockly.Connection.prototype.dispose=function(){if(this.targetConnection)throw"Disconnect connection before disposing of it.";this.inDB_&&this.db_.removeConnection_(this);Blockly.highlightedConnection_==this&&(Blockly.highlightedConnection_=null);Blockly.localConnection_==this&&(Blockly.localConnection_=null);this.dbOpposite_=this.db_=null};
Blockly.Connection.prototype.isSuperior=function(){return this.type==Blockly.INPUT_VALUE||this.type==Blockly.NEXT_STATEMENT};
Blockly.Comment.prototype.getText=function(){return this.textarea_?this.textarea_.value:this.text_};Blockly.Comment.prototype.setText=function(a){this.textarea_?this.textarea_.value=a:this.text_=a};Blockly.Comment.prototype.dispose=function(){this.block_.comment=null;Blockly.Icon.prototype.dispose.call(this)};Blockly.Connection=function(a,b){this.sourceBlock_=a;this.type=b;a.workspace.connectionDBList&&(this.db_=a.workspace.connectionDBList[b],this.dbOpposite_=a.workspace.connectionDBList[Blockly.OPPOSITE_TYPE[b]],this.hidden_=!this.db_)};Blockly.Connection.BOOLEAN=1;Blockly.Connection.STRING=2;Blockly.Connection.NUMBER=3;Blockly.Connection.prototype.targetConnection=null;Blockly.Connection.prototype.check_=null;Blockly.Connection.prototype.shadowDom_=null;Blockly.Connection.prototype.x_=0;
Blockly.Connection.prototype.y_=0;Blockly.Connection.prototype.inDB_=!1;Blockly.Connection.prototype.db_=null;Blockly.Connection.prototype.dbOpposite_=null;Blockly.Connection.prototype.hidden_=null;
Blockly.Connection.prototype.dispose=function(){if(this.targetConnection)throw"Disconnect connection before disposing of it.";this.inDB_&&this.db_.removeConnection_(this);Blockly.highlightedConnection_==this&&(Blockly.highlightedConnection_=null);Blockly.localConnection_==this&&(Blockly.localConnection_=null);this.dbOpposite_=this.db_=null};Blockly.Connection.prototype.isSuperior=function(){return this.type==Blockly.INPUT_VALUE||this.type==Blockly.NEXT_STATEMENT};
Blockly.Connection.prototype.connect=function(a){if(this.sourceBlock_==a.sourceBlock_)throw"Attempted to connect a block to itself.";if(this.sourceBlock_.workspace!==a.sourceBlock_.workspace)throw"Blocks are on different workspaces.";if(Blockly.OPPOSITE_TYPE[this.type]!=a.type)throw"Attempt to connect incompatible types.";if(this.type==Blockly.INPUT_VALUE||this.type==Blockly.OUTPUT_VALUE){if(this.targetConnection)throw"Source connection already connected (value).";if(a.targetConnection){var b=a.targetBlock();
b.setParent(null);if(b.isShadow())b.dispose();else{if(!b.outputConnection)throw"Orphan block does not have an output connection.";for(var c=this.sourceBlock_,d;d=Blockly.Connection.singleConnection_(c,b);)if(c=d.targetBlock(),!c||c.isShadow()){b.outputConnection.connect(d);b=null;break}b&&setTimeout(function(){b.outputConnection.bumpAwayFrom_(a)},Blockly.BUMP_DELAY)}}}else{if(this.targetConnection)throw"Source connection already connected (block).";if(a.targetConnection){if(this.type!=Blockly.PREVIOUS_STATEMENT)throw"Can only do a mid-stack connection with the top of a block.";
b=a.targetBlock();b.setParent(null);if(!b.previousConnection)throw"Orphan block does not have a previous connection.";for(c=this.sourceBlock_;c.nextConnection;)if(c.nextConnection.targetConnection)c=c.getNextBlock();else{b.previousConnection.checkType_(c.nextConnection)&&(c.nextConnection.connect(b.previousConnection),b=null);break}b&&setTimeout(function(){b.previousConnection.bumpAwayFrom_(a)},Blockly.BUMP_DELAY)}}this.isSuperior()?(c=this.sourceBlock_,d=a.sourceBlock_):(c=a.sourceBlock_,d=this.sourceBlock_);
@ -899,10 +899,11 @@ Blockly.Connection.prototype.moveTo=function(a,b){this.inDB_&&this.db_.removeCon
Blockly.Connection.prototype.highlight=function(){var a;this.type==Blockly.INPUT_VALUE||this.type==Blockly.OUTPUT_VALUE?(a=this.sourceBlock_.RTL?-Blockly.BlockSvg.TAB_WIDTH:Blockly.BlockSvg.TAB_WIDTH,a="m 0,0 v 5 c 0,10 "+-a+",-8 "+-a+",7.5 s "+a+",-2.5 "+a+",7.5 v 5"):a=this.sourceBlock_.RTL?"m 20,0 h -5 "+Blockly.BlockSvg.NOTCH_PATH_RIGHT+" h -5":"m -20,0 h 5 "+Blockly.BlockSvg.NOTCH_PATH_LEFT+" h 5";var b=this.sourceBlock_.getRelativeToSurfaceXY();Blockly.Connection.highlightedPath_=Blockly.createSvgElement("path",
{"class":"blocklyHighlightedConnectionPath",d:a,transform:"translate("+(this.x_-b.x)+","+(this.y_-b.y)+")"},this.sourceBlock_.getSvgRoot())};Blockly.Connection.prototype.unhighlight=function(){goog.dom.removeNode(Blockly.Connection.highlightedPath_);delete Blockly.Connection.highlightedPath_};
Blockly.Connection.prototype.tighten_=function(){var a=this.targetConnection.x_-this.x_,b=this.targetConnection.y_-this.y_;if(0!=a||0!=b){var c=this.targetBlock(),d=c.getSvgRoot();if(!d)throw"block is not rendered.";d=Blockly.getRelativeXY_(d);c.getSvgRoot().setAttribute("transform","translate("+(d.x-a)+","+(d.y-b)+")");c.moveConnections_(-a,-b)}};
Blockly.Connection.prototype.closest=function(a,b,c){function d(b){b=e[b];if((b.type==Blockly.OUTPUT_VALUE||b.type==Blockly.PREVIOUS_STATEMENT)&&b.targetConnection||b.type==Blockly.INPUT_VALUE&&b.targetConnection&&!b.targetBlock().isMovable()&&!b.targetBlock().isShadow()||!q.checkType_(b))return!0;var c=b.sourceBlock_;do{if(l==c)return!0;c=c.getParent()}while(c);var d=f-b.x_,c=g-b.y_,d=Math.sqrt(d*d+c*c);d<=a&&(k=b,a=d);return Math.abs(c)<a}if(this.targetConnection)return{connection:null,radius:a};
var e=this.dbOpposite_,f=this.x_+b,g=this.y_+c;b=0;for(var h=c=e.length-2;b<h;)e[h].y_<g?b=h:c=h,h=Math.floor((b+c)/2);c=b=h;var k=null,l=this.sourceBlock_,q=this;if(e.length){for(;0<=b&&d(b);)b--;do c++;while(c<e.length&&d(c))}return{connection:k,radius:a}};
Blockly.Connection.prototype.closest=function(a,b,c){function d(b){b=e[b];if((b.type==Blockly.OUTPUT_VALUE||b.type==Blockly.PREVIOUS_STATEMENT)&&b.targetConnection||b.type==Blockly.INPUT_VALUE&&b.targetConnection&&!b.targetBlock().isMovable()&&!b.targetBlock().isShadow()||!m.checkType_(b))return!0;var c=b.sourceBlock_;do{if(l==c)return!0;c=c.getParent()}while(c);var d=f-b.x_,c=g-b.y_,d=Math.sqrt(d*d+c*c);d<=a&&(k=b,a=d);return Math.abs(c)<a}if(this.targetConnection)return{connection:null,radius:a};
var e=this.dbOpposite_,f=this.x_+b,g=this.y_+c;b=0;for(var h=c=e.length-2;b<h;)e[h].y_<g?b=h:c=h,h=Math.floor((b+c)/2);c=b=h;var k=null,l=this.sourceBlock_,m=this;if(e.length){for(;0<=b&&d(b);)b--;do c++;while(c<e.length&&d(c))}return{connection:k,radius:a}};
Blockly.Connection.prototype.checkType_=function(a){var b=this.targetBlock();if(b&&!b.isMovable()&&!this.sourceBlock_.isMovable()||(b=a.targetBlock())&&!b.isMovable()&&!a.sourceBlock_.isMovable())return!1;if(!this.check_||!a.check_)return!0;for(b=0;b<this.check_.length;b++)if(-1!=a.check_.indexOf(this.check_[b]))return!0;return!1};
Blockly.Connection.prototype.setCheck=function(a){a?(goog.isArray(a)||(a=[a]),this.check_=a,this.targetConnection&&!this.checkType_(this.targetConnection)&&(this.isSuperior()?this.targetBlock().setParent(null):this.sourceBlock_.setParent(null),this.sourceBlock_.bumpNeighbours_())):this.check_=null;return this};Blockly.Connection.prototype.setShadowDom=function(a){this.shadowDom_=a};Blockly.Connection.prototype.getShadowDom=function(){return this.shadowDom_};
Blockly.Connection.prototype.setCheck=function(a){a?(goog.isArray(a)||(a=[a]),this.check_=a,this.targetConnection&&!this.checkType_(this.targetConnection)&&(this.isSuperior()?this.targetBlock().setParent(null):this.sourceBlock_.setParent(null),this.sourceBlock_.bumpNeighbours_())):this.check_=null;return this};
Blockly.Connection.prototype.getOutputShape=function(){return this.check_?-1!==this.check_.indexOf("Boolean")?Blockly.Connection.BOOLEAN:-1!==this.check_.indexOf("String")?Blockly.Connection.STRING:Blockly.Connection.NUMBER:Blockly.Connection.NUMBER};Blockly.Connection.prototype.setShadowDom=function(a){this.shadowDom_=a};Blockly.Connection.prototype.getShadowDom=function(){return this.shadowDom_};
Blockly.Connection.prototype.neighbours_=function(a){function b(b){var f=d-c[b].x_,g=e-c[b].y_;Math.sqrt(f*f+g*g)<=a&&k.push(c[b]);return g<a}for(var c=this.dbOpposite_,d=this.x_,e=this.y_,f=0,g=c.length-2,h=g;f<h;)c[h].y_<e?f=h:g=h,h=Math.floor((f+g)/2);var g=f=h,k=[];if(c.length){for(;0<=f&&b(f);)f--;do g++;while(g<c.length&&b(g))}return k};Blockly.Connection.prototype.setHidden=function(a){(this.hidden_=a)&&this.inDB_?this.db_.removeConnection_(this):a||this.inDB_||this.db_.addConnection_(this)};
Blockly.Connection.prototype.hideAll=function(){this.setHidden(!0);if(this.targetConnection)for(var a=this.targetBlock().getDescendants(),b=0;b<a.length;b++){for(var c=a[b],d=c.getConnections_(!0),e=0;e<d.length;e++)d[e].setHidden(!0);c=c.getIcons();for(d=0;d<c.length;d++)c[d].setVisible(!1)}};
Blockly.Connection.prototype.unhideAll=function(){this.setHidden(!1);var a=[];if(this.type!=Blockly.INPUT_VALUE&&this.type!=Blockly.NEXT_STATEMENT)return a;var b=this.targetBlock();if(b){var c;b.isCollapsed()?(c=[],b.outputConnection&&c.push(b.outputConnection),b.nextConnection&&c.push(b.nextConnection),b.previousConnection&&c.push(b.previousConnection)):c=b.getConnections_(!0);for(var d=0;d<c.length;d++)a.push.apply(a,c[d].unhideAll());0==a.length&&(a[0]=b)}return a};Blockly.ConnectionDB=function(){};
@ -978,7 +979,7 @@ Blockly.Xml.textToDom=function(a){a=(new DOMParser).parseFromString(a,"text/xml"
Blockly.Xml.domToWorkspace=function(a,b){var c;a.RTL&&(c=a.getWidth());Blockly.Field.startCache();for(var d=b.childNodes.length,e=0;e<d;e++){var f=b.childNodes[e],g=f.nodeName.toLowerCase();if("block"==g||"shadow"==g){var g=Blockly.Xml.domToBlock(a,f),h=parseInt(f.getAttribute("x"),10),f=parseInt(f.getAttribute("y"),10);isNaN(h)||isNaN(f)||g.moveBy(a.RTL?c-h:h,f)}}Blockly.Field.stopCache()};
Blockly.Xml.domToBlock=function(a,b){var c=Blockly.Xml.domToBlockHeadless_(a,b);if(a.rendered){c.setConnectionsHidden(!0);for(var d=c.getDescendants(),e=d.length-1;0<=e;e--)d[e].initSvg();for(e=d.length-1;0<=e;e--)d[e].render(!1);setTimeout(function(){c.workspace&&c.setConnectionsHidden(!1)},1);c.updateDisabled();Blockly.fireUiEvent(window,"resize")}return c};
Blockly.Xml.domToBlockHeadless_=function(a,b){var c=null,d=b.getAttribute("type");if(!d)throw"Block type unspecified: \n"+b.outerHTML;for(var e=b.getAttribute("id"),c=a.newBlock(d,e),f=null,e=0,g;g=b.childNodes[e];e++)if(3!=g.nodeType){for(var h=f=null,k=0,l;l=g.childNodes[k];k++)1==l.nodeType&&("block"==l.nodeName.toLowerCase()?f=l:"shadow"==l.nodeName.toLowerCase()&&(h=l));!f&&h&&(f=h);k=g.getAttribute("name");switch(g.nodeName.toLowerCase()){case "mutation":c.domToMutation&&(c.domToMutation(g),
c.initSvg&&c.initSvg());break;case "comment":c.setCommentText(g.textContent);var q=g.getAttribute("pinned");q&&!c.isInFlyout&&setTimeout(function(){c.comment&&c.comment.setVisible&&c.comment.setVisible("true"==q)},1);f=parseInt(g.getAttribute("w"),10);g=parseInt(g.getAttribute("h"),10);!isNaN(f)&&!isNaN(g)&&c.comment&&c.comment.setVisible&&c.comment.setBubbleSize(f,g);break;case "data":c.data=g.textContent;break;case "title":case "field":f=c.getField(k);if(!f){console.warn("Ignoring non-existent field "+
c.initSvg&&c.initSvg());break;case "comment":c.setCommentText(g.textContent);var m=g.getAttribute("pinned");m&&!c.isInFlyout&&setTimeout(function(){c.comment&&c.comment.setVisible&&c.comment.setVisible("true"==m)},1);f=parseInt(g.getAttribute("w"),10);g=parseInt(g.getAttribute("h"),10);!isNaN(f)&&!isNaN(g)&&c.comment&&c.comment.setVisible&&c.comment.setBubbleSize(f,g);break;case "data":c.data=g.textContent;break;case "title":case "field":f=c.getField(k);if(!f){console.warn("Ignoring non-existent field "+
k+" in block "+d);break}f.setValue(g.textContent);break;case "value":case "statement":g=c.getInput(k);if(!g){console.warn("Ignoring non-existent input "+k+" in block "+d);break}h&&g.connection.setShadowDom(h);if(f)if(f=Blockly.Xml.domToBlockHeadless_(a,f),f.outputConnection)g.connection.connect(f.outputConnection);else if(f.previousConnection)g.connection.connect(f.previousConnection);else throw"Child block does not have output or previous statement.";break;case "next":h&&c.nextConnection&&c.nextConnection.setShadowDom(h);
if(f){if(!c.nextConnection)throw"Next statement does not exist.";if(c.nextConnection.targetConnection)throw"Next statement is already connected.";f=Blockly.Xml.domToBlockHeadless_(a,f);if(!f.previousConnection)throw"Next block does not have previous statement.";c.nextConnection.connect(f.previousConnection)}break;default:console.warn("Ignoring unknown tag: "+g.nodeName)}}(d=b.getAttribute("inline"))&&c.setInputsInline("true"==d);(d=b.getAttribute("disabled"))&&c.setDisabled("true"==d);(d=b.getAttribute("deletable"))&&
c.setDeletable("true"==d);(d=b.getAttribute("movable"))&&c.setMovable("true"==d);(d=b.getAttribute("editable"))&&c.setEditable("true"==d);(d=b.getAttribute("collapsed"))&&c.setCollapsed("true"==d);"shadow"==b.nodeName.toLowerCase()&&c.setShadow(!0);c.validate&&c.validate();return c};Blockly.Xml.deleteNext=function(a){for(var b=0,c;c=a.childNodes[b];b++)if("next"==c.nodeName.toLowerCase()){a.removeChild(c);break}};goog.global.Blockly||(goog.global.Blockly={});
@ -1005,9 +1006,9 @@ Blockly.WorkspaceSvg.prototype.onMouseDown_=function(a){this.markFocused();Block
this.startDragMetrics=this.getMetrics(),this.startScrollX=this.scrollX,this.startScrollY=this.scrollY,"mouseup"in Blockly.bindEvent_.TOUCH_MAP&&(Blockly.onTouchUpWrapper_=Blockly.bindEvent_(document,"mouseup",null,Blockly.onMouseUp_)),Blockly.onMouseMoveWrapper_=Blockly.bindEvent_(document,"mousemove",null,Blockly.onMouseMove_)),a.stopPropagation())};
Blockly.WorkspaceSvg.prototype.startDrag=function(a,b,c){a=Blockly.mouseToSvg(a,this.getParentSvg());a.x/=this.scale;a.y/=this.scale;this.dragDeltaX_=b-a.x;this.dragDeltaY_=c-a.y};Blockly.WorkspaceSvg.prototype.moveDrag=function(a){a=Blockly.mouseToSvg(a,this.getParentSvg());a.x/=this.scale;a.y/=this.scale;return new goog.math.Coordinate(this.dragDeltaX_+a.x,this.dragDeltaY_+a.y)};
Blockly.WorkspaceSvg.prototype.onMouseWheel_=function(a){Blockly.terminateDrag_();var b=0<a.deltaY?-1:1,c=Blockly.mouseToSvg(a,this.getParentSvg());this.zoom(c.x,c.y,b);a.preventDefault()};Blockly.WorkspaceSvg.prototype.cleanUp_=function(){for(var a=this.getTopBlocks(!0),b=0,c=0,d;d=a[c];c++){var e=d.getRelativeToSurfaceXY();d.moveBy(-e.x,b-e.y);d.snapToGrid();b=d.getRelativeToSurfaceXY().y+d.getHeightWidth().height+Blockly.BlockSvg.MIN_BLOCK_Y}Blockly.fireUiEvent(window,"resize");this.fireChangeEvent()};
Blockly.WorkspaceSvg.prototype.showContextMenu_=function(a){function b(a){if(a.isDeletable())q=q.concat(a.getDescendants());else{a=a.getChildren();for(var c=0;c<a.length;c++)b(a[c])}}function c(){var a=q.shift();a&&(a.workspace?(a.dispose(!1,!0),setTimeout(c,10)):c())}if(!this.options.readOnly&&!this.isFlyout){var d=[],e=this.getTopBlocks(!0),f={};f.text=Blockly.Msg.CLEAN_UP;f.enabled=1<e.length;f.callback=this.cleanUp_.bind(this);d.push(f);if(this.options.collapse){for(var g=f=!1,h=0;h<e.length;h++)for(var k=
e[h];k;)k.isCollapsed()?f=!0:g=!0,k=k.getNextBlock();var l=function(a){for(var b=0,c=0;c<e.length;c++)for(var d=e[c];d;)setTimeout(d.setCollapsed.bind(d,a),b),d=d.getNextBlock(),b+=10},g={enabled:g};g.text=Blockly.Msg.COLLAPSE_ALL;g.callback=function(){l(!0)};d.push(g);f={enabled:f};f.text=Blockly.Msg.EXPAND_ALL;f.callback=function(){l(!1)};d.push(f)}for(var q=[],h=0;h<e.length;h++)b(e[h]);f={text:1>=q.length?Blockly.Msg.DELETE_BLOCK:Blockly.Msg.DELETE_X_BLOCKS.replace("%1",String(q.length)),enabled:0<
q.length,callback:function(){(2>q.length||window.confirm(Blockly.Msg.DELETE_ALL_BLOCKS.replace("%1",String(q.length))))&&c()}};d.push(f);Blockly.ContextMenu.show(a,d,this.RTL)}};Blockly.WorkspaceSvg.prototype.loadAudio_=function(a,b){if(a.length){try{var c=new window.Audio}catch(h){return}for(var d,e=0;e<a.length;e++){var f=a[e],g=f.match(/\.(\w+)$/);if(g&&c.canPlayType("audio/"+g[1])){d=new window.Audio(f);break}}d&&d.play&&(this.SOUNDS_[b]=d)}};
Blockly.WorkspaceSvg.prototype.showContextMenu_=function(a){function b(a){if(a.isDeletable())m=m.concat(a.getDescendants());else{a=a.getChildren();for(var c=0;c<a.length;c++)b(a[c])}}function c(){var a=m.shift();a&&(a.workspace?(a.dispose(!1,!0),setTimeout(c,10)):c())}if(!this.options.readOnly&&!this.isFlyout){var d=[],e=this.getTopBlocks(!0),f={};f.text=Blockly.Msg.CLEAN_UP;f.enabled=1<e.length;f.callback=this.cleanUp_.bind(this);d.push(f);if(this.options.collapse){for(var g=f=!1,h=0;h<e.length;h++)for(var k=
e[h];k;)k.isCollapsed()?f=!0:g=!0,k=k.getNextBlock();var l=function(a){for(var b=0,c=0;c<e.length;c++)for(var d=e[c];d;)setTimeout(d.setCollapsed.bind(d,a),b),d=d.getNextBlock(),b+=10},g={enabled:g};g.text=Blockly.Msg.COLLAPSE_ALL;g.callback=function(){l(!0)};d.push(g);f={enabled:f};f.text=Blockly.Msg.EXPAND_ALL;f.callback=function(){l(!1)};d.push(f)}for(var m=[],h=0;h<e.length;h++)b(e[h]);f={text:1>=m.length?Blockly.Msg.DELETE_BLOCK:Blockly.Msg.DELETE_X_BLOCKS.replace("%1",String(m.length)),enabled:0<
m.length,callback:function(){(2>m.length||window.confirm(Blockly.Msg.DELETE_ALL_BLOCKS.replace("%1",String(m.length))))&&c()}};d.push(f);Blockly.ContextMenu.show(a,d,this.RTL)}};Blockly.WorkspaceSvg.prototype.loadAudio_=function(a,b){if(a.length){try{var c=new window.Audio}catch(h){return}for(var d,e=0;e<a.length;e++){var f=a[e],g=f.match(/\.(\w+)$/);if(g&&c.canPlayType("audio/"+g[1])){d=new window.Audio(f);break}}d&&d.play&&(this.SOUNDS_[b]=d)}};
Blockly.WorkspaceSvg.prototype.preloadAudio_=function(){for(var a in this.SOUNDS_){var b=this.SOUNDS_[a];b.volume=.01;b.play();b.pause();if(goog.userAgent.IPAD||goog.userAgent.IPHONE)break}};
Blockly.WorkspaceSvg.prototype.playAudio=function(a,b){var c=this.SOUNDS_[a];c?(c=goog.userAgent.DOCUMENT_MODE&&9===goog.userAgent.DOCUMENT_MODE||goog.userAgent.IPAD||goog.userAgent.ANDROID?c:c.cloneNode(),c.volume=void 0===b?1:b,c.play()):this.options.parentWorkspace&&this.options.parentWorkspace.playAudio(a,b)};
Blockly.WorkspaceSvg.prototype.updateToolbox=function(a){if(a=Blockly.parseToolboxTree_(a)){if(!this.options.languageTree)throw"Existing toolbox is null. Can't create new toolbox.";if(this.options.hasCategories){if(!this.toolbox_)throw"Existing toolbox has no categories. Can't change mode.";this.options.languageTree=a;this.toolbox_.populate_(a);this.toolbox_.addColour_()}else{if(!this.flyout_)throw"Existing toolbox has categories. Can't change mode.";this.options.languageTree=a;this.flyout_.show(a.childNodes)}}else if(this.options.languageTree)throw"Can't nullify an existing toolbox.";
@ -1032,7 +1033,7 @@ goog.Timer.callOnce(this.block_.bumpNeighbours_,Blockly.BUMP_DELAY,this.block_))
Blockly.Warning.prototype.drawIcon_=function(a){Blockly.createSvgElement("path",{"class":"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},a);Blockly.createSvgElement("path",{"class":"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},a);Blockly.createSvgElement("rect",{"class":"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},a)};
Blockly.Warning.textToDom_=function(a){var b=Blockly.createSvgElement("text",{"class":"blocklyText blocklyBubbleText",y:Blockly.Bubble.BORDER_WIDTH},null);a=a.split("\n");for(var c=0;c<a.length;c++){var d=Blockly.createSvgElement("tspan",{dy:"1em",x:Blockly.Bubble.BORDER_WIDTH},b),e=document.createTextNode(a[c]);d.appendChild(e)}return b};
Blockly.Warning.prototype.setVisible=function(a){if(a!=this.isVisible())if(a){a=Blockly.Warning.textToDom_(this.getText());this.bubble_=new Blockly.Bubble(this.block_.workspace,a,this.block_.svgPath_,this.iconX_,this.iconY_,null,null);if(this.block_.RTL)for(var b=a.getBBox().width,c=0,d;d=a.childNodes[c];c++)d.setAttribute("text-anchor","end"),d.setAttribute("x",b+Blockly.Bubble.BORDER_WIDTH);this.updateColour();a=this.bubble_.getBubbleSize();this.bubble_.setBubbleSize(a.width,a.height)}else this.bubble_.dispose(),
this.body_=this.bubble_=null};Blockly.Warning.prototype.bodyFocus_=function(a){this.bubble_.promote_()};Blockly.Warning.prototype.setText=function(a,b){this.text_[b]!=a&&(a?this.text_[b]=a:delete this.text_[b],this.isVisible()&&(this.setVisible(!1),this.setVisible(!0)))};Blockly.Warning.prototype.getText=function(){var a=[],b;for(b in this.text_)a.push(this.text_[b]);return a.join("\n")};Blockly.Warning.prototype.dispose=function(){this.block_.warning=null;Blockly.Icon.prototype.dispose.call(this)};Blockly.Block=function(a,b,c){this.id=c||Blockly.genUid();goog.asserts.assert(!Blockly.Block.getById(this.id),'Error: Block "%s" already exists.',this.id);Blockly.Block.BlockDB_[this.id]=this;this.previousConnection=this.nextConnection=this.outputConnection=null;this.inputList=[];this.inputsInline=void 0;this.disabled=this.rendered=!1;this.tooltip="";this.contextMenu=!0;this.parentBlock_=null;this.childBlocks_=[];this.editable_=this.movable_=this.deletable_=!0;this.collapsed_=this.isShadow_=!1;this.comment=
this.body_=this.bubble_=null};Blockly.Warning.prototype.bodyFocus_=function(a){this.bubble_.promote_()};Blockly.Warning.prototype.setText=function(a,b){this.text_[b]!=a&&(a?this.text_[b]=a:delete this.text_[b],this.isVisible()&&(this.setVisible(!1),this.setVisible(!0)))};Blockly.Warning.prototype.getText=function(){var a=[],b;for(b in this.text_)a.push(this.text_[b]);return a.join("\n")};Blockly.Warning.prototype.dispose=function(){this.block_.warning=null;Blockly.Icon.prototype.dispose.call(this)};Blockly.Block=function(a,b,c){this.id=c||Blockly.genUid();goog.asserts.assert(!Blockly.Block.getById(this.id),'Error: Block "%s" already exists.',this.id);Blockly.Block.BlockDB_[this.id]=this;this.previousConnection=this.nextConnection=this.outputConnection=null;this.inputList=[];this.inputsInline=!0;this.disabled=this.rendered=!1;this.tooltip="";this.contextMenu=!0;this.parentBlock_=null;this.childBlocks_=[];this.editable_=this.movable_=this.deletable_=!0;this.collapsed_=this.isShadow_=!1;this.comment=
null;this.xy_=new goog.math.Coordinate(0,0);this.workspace=a;this.isInFlyout=a.isFlyout;this.RTL=a.RTL;b&&(this.type=b,c=Blockly.Blocks[b],goog.asserts.assertObject(c,'Error: "%s" is an unknown language block.',b),goog.mixin(this,c));a.addTopBlock(this);goog.isFunction(this.init)&&this.init();this.inputsInlineDefault=this.inputsInline};Blockly.Block.obtain=function(a,b){console.warn("Deprecated call to Blockly.Block.obtain, use workspace.newBlock instead.");return a.newBlock(b)};
Blockly.Block.prototype.data=null;Blockly.Block.prototype.colour_="#000000";
Blockly.Block.prototype.dispose=function(a,b,c){this.unplug(a,!1);this.workspace&&!c&&(this.workspace.removeTopBlock(this),this.workspace=null);Blockly.selected==this&&(Blockly.selected=null);for(a=this.childBlocks_.length-1;0<=a;a--)this.childBlocks_[a].dispose(!1);for(a=0;b=this.inputList[a];a++)b.dispose();this.inputList.length=0;b=this.getConnections_(!0);for(a=0;a<b.length;a++)c=b[a],c.targetConnection&&c.disconnect(),b[a].dispose();delete Blockly.Block.BlockDB_[this.id]};
@ -1070,8 +1071,7 @@ Blockly.Block.prototype.getInputTargetBlock=function(a){return(a=this.getInput(a
Blockly.Block.prototype.moveBy=function(a,b){this.xy_.translate(a,b)};Blockly.Block.BlockDB_=Object.create(null);Blockly.Block.getById=function(a){return Blockly.Block.BlockDB_[a]||null};Blockly.ContextMenu={};Blockly.ContextMenu.currentBlock=null;
Blockly.ContextMenu.show=function(a,b,c){Blockly.WidgetDiv.show(Blockly.ContextMenu,c,null);if(b.length){var d=new goog.ui.Menu;d.setRightToLeft(c);for(var e=0,f;f=b[e];e++){var g=new goog.ui.MenuItem(f.text);g.setRightToLeft(c);d.addChild(g,!0);g.setEnabled(f.enabled);f.enabled&&goog.events.listen(g,goog.ui.Component.EventType.ACTION,f.callback)}goog.events.listen(d,goog.ui.Component.EventType.ACTION,Blockly.ContextMenu.hide);b=goog.dom.getViewportSize();f=goog.style.getViewportPageOffset(document);
d.render(Blockly.WidgetDiv.DIV);var h=d.getElement();Blockly.addClass_(h,"blocklyContextMenu");var g=goog.style.getSize(h),e=a.clientX+f.x,k=a.clientY+f.y;a.clientY+g.height>=b.height&&(k-=g.height);c?g.width>=a.clientX&&(e+=g.width):a.clientX+g.width>=b.width&&(e-=g.width);Blockly.WidgetDiv.position(e,k,b,f,c);d.setAllowAutoFocus(!0);setTimeout(function(){h.focus()},1);Blockly.ContextMenu.currentBlock=null}else Blockly.ContextMenu.hide()};
Blockly.ContextMenu.hide=function(){Blockly.WidgetDiv.hideIfOwner(Blockly.ContextMenu);Blockly.ContextMenu.currentBlock=null};Blockly.ContextMenu.callbackFactory=function(a,b){return function(){var c=Blockly.Xml.domToBlock(a.workspace,b),d=a.getRelativeToSurfaceXY();d.x=a.RTL?d.x-Blockly.SNAP_RADIUS:d.x+Blockly.SNAP_RADIUS;d.y+=2*Blockly.SNAP_RADIUS;c.moveBy(d.x,d.y);c.select()}};Blockly.BlockSvg=function(a,b,c){this.svgGroup_=Blockly.createSvgElement("g",{},null);this.svgPathDark_=Blockly.createSvgElement("path",{"class":"blocklyPathDark",transform:"translate(1,1)"},this.svgGroup_);this.svgPath_=Blockly.createSvgElement("path",{"class":"blocklyPath"},this.svgGroup_);this.svgPathLight_=Blockly.createSvgElement("path",{"class":"blocklyPathLight"},this.svgGroup_);this.svgPath_.tooltip=this;Blockly.Tooltip.bindMouseEvents(this.svgPath_);Blockly.BlockSvg.superClass_.constructor.call(this,
a,b,c)};goog.inherits(Blockly.BlockSvg,Blockly.Block);Blockly.BlockSvg.prototype.height=0;Blockly.BlockSvg.prototype.width=0;Blockly.BlockSvg.prototype.dragStartXY_=null;Blockly.BlockSvg.INLINE=-1;
Blockly.ContextMenu.hide=function(){Blockly.WidgetDiv.hideIfOwner(Blockly.ContextMenu);Blockly.ContextMenu.currentBlock=null};Blockly.ContextMenu.callbackFactory=function(a,b){return function(){var c=Blockly.Xml.domToBlock(a.workspace,b),d=a.getRelativeToSurfaceXY();d.x=a.RTL?d.x-Blockly.SNAP_RADIUS:d.x+Blockly.SNAP_RADIUS;d.y+=2*Blockly.SNAP_RADIUS;c.moveBy(d.x,d.y);c.select()}};Blockly.BlockSvg=function(a,b,c){this.svgGroup_=Blockly.createSvgElement("g",{},null);this.svgPath_=Blockly.createSvgElement("path",{"class":"blocklyPath"},this.svgGroup_);this.svgPath_.tooltip=this;Blockly.Tooltip.bindMouseEvents(this.svgPath_);Blockly.BlockSvg.superClass_.constructor.call(this,a,b,c)};goog.inherits(Blockly.BlockSvg,Blockly.Block);Blockly.BlockSvg.prototype.height=0;Blockly.BlockSvg.prototype.width=0;Blockly.BlockSvg.prototype.dragStartXY_=null;Blockly.BlockSvg.INLINE=-1;
Blockly.BlockSvg.prototype.initSvg=function(){goog.asserts.assert(this.workspace.rendered,"Workspace is headless.");for(var a=0,b;b=this.inputList[a];a++)b.init();b=this.getIcons();for(a=0;a<b.length;a++)b[a].createIcon();this.updateColour();this.updateMovable();if(!this.workspace.options.readOnly&&!this.eventsInit_){Blockly.bindEvent_(this.getSvgRoot(),"mousedown",this,this.onMouseDown_);var c=this;Blockly.bindEvent_(this.getSvgRoot(),"touchstart",null,function(a){Blockly.longStart_(a,c)})}goog.isFunction(this.onchange)&&
!this.eventsInit_&&(this.onchangeWrapper_=Blockly.bindEvent_(this.workspace.getCanvas(),"blocklyWorkspaceChange",this,this.onchange));this.eventsInit_=!0;this.getSvgRoot().parentNode||this.workspace.getCanvas().appendChild(this.getSvgRoot())};Blockly.BlockSvg.prototype.select=function(){Blockly.selected&&Blockly.selected.unselect();Blockly.selected=this;this.addSelect();Blockly.fireUiEvent(this.workspace.getCanvas(),"blocklySelectChange")};
Blockly.BlockSvg.prototype.unselect=function(){Blockly.selected=null;this.removeSelect();Blockly.fireUiEvent(this.workspace.getCanvas(),"blocklySelectChange")};Blockly.BlockSvg.prototype.mutator=null;Blockly.BlockSvg.prototype.comment=null;Blockly.BlockSvg.prototype.warning=null;Blockly.BlockSvg.prototype.getIcons=function(){var a=[];this.mutator&&a.push(this.mutator);this.comment&&a.push(this.comment);this.warning&&a.push(this.warning);return a};Blockly.BlockSvg.onMouseUpWrapper_=null;
@ -1082,76 +1082,59 @@ Blockly.BlockSvg.prototype.setParent=function(a){var b=this.getSvgRoot();if(this
Blockly.BlockSvg.prototype.getRelativeToSurfaceXY=function(){var a=0,b=0,c=this.getSvgRoot();if(c){do var d=Blockly.getRelativeXY_(c),a=a+d.x,b=b+d.y,c=c.parentNode;while(c&&c!=this.workspace.getCanvas())}return new goog.math.Coordinate(a,b)};Blockly.BlockSvg.prototype.moveBy=function(a,b){var c=this.getRelativeToSurfaceXY();this.getSvgRoot().setAttribute("transform","translate("+(c.x+a)+","+(c.y+b)+")");this.moveConnections_(a,b)};
Blockly.BlockSvg.prototype.snapToGrid=function(){if(this.workspace&&0==Blockly.dragMode_&&!this.getParent()&&!this.isInFlyout&&this.workspace.options.gridOptions&&this.workspace.options.gridOptions.snap){var a=this.workspace.options.gridOptions.spacing,b=a/2,c=this.getRelativeToSurfaceXY(),d=Math.round((c.x-b)/a)*a+b-c.x,a=Math.round((c.y-b)/a)*a+b-c.y,d=Math.round(d),a=Math.round(a);0==d&&0==a||this.moveBy(d,a)}};
Blockly.BlockSvg.prototype.getHeightWidth=function(){var a=this.height,b=this.width,c=this.getNextBlock();c?(c=c.getHeightWidth(),a+=c.height-4,b=Math.max(b,c.width)):this.nextConnection||this.outputConnection||(a+=2);return{height:a,width:b}};
Blockly.BlockSvg.prototype.setCollapsed=function(a){if(this.collapsed_!=a){for(var b=[],c=0,d;d=this.inputList[c];c++)b.push.apply(b,d.setVisible(!a));if(a){d=this.getIcons();for(c=0;c<d.length;c++)d[c].setVisible(!1);c=this.toString(Blockly.COLLAPSE_CHARS);this.appendDummyInput("_TEMP_COLLAPSED_INPUT").appendField(c).init()}else this.removeInput("_TEMP_COLLAPSED_INPUT"),this.setWarningText(null);Blockly.BlockSvg.superClass_.setCollapsed.call(this,a);b.length||(b[0]=this);if(this.rendered)for(c=0;a=
b[c];c++)a.render();this.workspace.fireChangeEvent()}};Blockly.BlockSvg.prototype.tab=function(a,b){for(var c=[],d=0,e;e=this.inputList[d];d++){for(var f=0,g;g=e.fieldRow[f];f++)g instanceof Blockly.FieldTextInput&&c.push(g);e.connection&&(e=e.connection.targetBlock())&&c.push(e)}d=c.indexOf(a);-1==d&&(d=b?-1:c.length);(c=c[b?d+1:d-1])?c instanceof Blockly.Field?c.showEditor_():c.tab(null,b):(c=this.getParent())&&c.tab(this,b)};
Blockly.BlockSvg.prototype.tab=function(a,b){for(var c=[],d=0,e;e=this.inputList[d];d++){for(var f=0,g;g=e.fieldRow[f];f++)g instanceof Blockly.FieldTextInput&&c.push(g);e.connection&&(e=e.connection.targetBlock())&&c.push(e)}d=c.indexOf(a);-1==d&&(d=b?-1:c.length);(c=c[b?d+1:d-1])?c instanceof Blockly.Field?c.showEditor_():c.tab(null,b):(c=this.getParent())&&c.tab(this,b)};
Blockly.BlockSvg.prototype.onMouseDown_=function(a){if(!this.isInFlyout)if(this.workspace.markFocused(),Blockly.svgResize(this.workspace),Blockly.terminateDrag_(),this.select(),Blockly.hideChaff(),Blockly.isRightButton(a))this.showContextMenu_(a);else if(this.isMovable()){Blockly.removeAllRanges();Blockly.Css.setCursor(Blockly.Css.Cursor.CLOSED);this.dragStartXY_=this.getRelativeToSurfaceXY();this.workspace.startDrag(a,this.dragStartXY_.x,this.dragStartXY_.y);Blockly.dragMode_=1;Blockly.BlockSvg.onMouseUpWrapper_=
Blockly.bindEvent_(document,"mouseup",this,this.onMouseUp_);Blockly.BlockSvg.onMouseMoveWrapper_=Blockly.bindEvent_(document,"mousemove",this,this.onMouseMove_);this.draggedBubbles_=[];for(var b=this.getDescendants(),c=0,d;d=b[c];c++){d=d.getIcons();for(var e=0;e<d.length;e++){var f=d[e].getIconLocation();f.bubble=d[e];this.draggedBubbles_.push(f)}}}else return;a.stopPropagation()};
Blockly.BlockSvg.prototype.onMouseUp_=function(a){Blockly.terminateDrag_();Blockly.selected&&Blockly.highlightedConnection_?(Blockly.localConnection_.connect(Blockly.highlightedConnection_),this.rendered&&(Blockly.localConnection_.isSuperior()?Blockly.highlightedConnection_:Blockly.localConnection_).sourceBlock_.connectionUiEffect(),this.workspace.trashcan&&this.workspace.trashcan.close()):!this.getParent()&&Blockly.selected.isDeletable()&&this.workspace.isDeleteArea(a)&&((a=this.workspace.trashcan)&&
goog.Timer.callOnce(a.close,100,a),Blockly.selected.dispose(!1,!0),Blockly.fireUiEvent(window,"resize"));Blockly.highlightedConnection_&&(Blockly.highlightedConnection_.unhighlight(),Blockly.highlightedConnection_=null);Blockly.Css.setCursor(Blockly.Css.Cursor.OPEN)};Blockly.BlockSvg.prototype.showHelp_=function(){var a=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;a&&window.open(a)};
Blockly.BlockSvg.prototype.showContextMenu_=function(a){if(!this.workspace.options.readOnly&&this.contextMenu){var b=this,c=[];if(this.isDeletable()&&this.isMovable()&&!b.isInFlyout){var d={text:Blockly.Msg.DUPLICATE_BLOCK,enabled:!0,callback:function(){Blockly.duplicate_(b)}};this.getDescendants().length>this.workspace.remainingCapacity()&&(d.enabled=!1);c.push(d);this.isEditable()&&!this.collapsed_&&this.workspace.options.comments&&(d={enabled:!goog.userAgent.IE},this.comment?(d.text=Blockly.Msg.REMOVE_COMMENT,
d.callback=function(){b.setCommentText(null)}):(d.text=Blockly.Msg.ADD_COMMENT,d.callback=function(){b.setCommentText("")}),c.push(d));if(!this.collapsed_)for(d=1;d<this.inputList.length;d++)if(this.inputList[d-1].type!=Blockly.NEXT_STATEMENT&&this.inputList[d].type!=Blockly.NEXT_STATEMENT){var d={enabled:!0},e=this.getInputsInline();d.text=e?Blockly.Msg.EXTERNAL_INPUTS:Blockly.Msg.INLINE_INPUTS;d.callback=function(){b.setInputsInline(!e)};c.push(d);break}this.workspace.options.collapse&&(this.collapsed_?
(d={enabled:!0},d.text=Blockly.Msg.EXPAND_BLOCK,d.callback=function(){b.setCollapsed(!1)}):(d={enabled:!0},d.text=Blockly.Msg.COLLAPSE_BLOCK,d.callback=function(){b.setCollapsed(!0)}),c.push(d));this.workspace.options.disable&&(d={text:this.disabled?Blockly.Msg.ENABLE_BLOCK:Blockly.Msg.DISABLE_BLOCK,enabled:!this.getInheritedDisabled(),callback:function(){b.setDisabled(!b.disabled)}},c.push(d));var d=this.getDescendants().length,f=this.getNextBlock();f&&(d-=f.getDescendants().length);d={text:1==d?
Blockly.Msg.DELETE_BLOCK:Blockly.Msg.DELETE_X_BLOCKS.replace("%1",String(d)),enabled:!0,callback:function(){b.dispose(!0,!0)}};c.push(d)}d={enabled:!(goog.isFunction(this.helpUrl)?!this.helpUrl():!this.helpUrl)};d.text=Blockly.Msg.HELP;d.callback=function(){b.showHelp_()};c.push(d);this.customContextMenu&&!b.isInFlyout&&this.customContextMenu(c);Blockly.ContextMenu.show(a,c,this.RTL);Blockly.ContextMenu.currentBlock=this}};
Blockly.BlockSvg.prototype.moveConnections_=function(a,b){if(this.rendered){for(var c=this.getConnections_(!1),d=0;d<c.length;d++)c[d].moveBy(a,b);c=this.getIcons();for(d=0;d<c.length;d++)c[d].computeIconLocation();for(d=0;d<this.childBlocks_.length;d++)this.childBlocks_[d].moveConnections_(a,b)}};Blockly.BlockSvg.prototype.setDragging_=function(a){a?this.addDragging():this.removeDragging();for(var b=0;b<this.childBlocks_.length;b++)this.childBlocks_[b].setDragging_(a)};
goog.Timer.callOnce(a.close,100,a),Blockly.selected.dispose(!1,!0),Blockly.fireUiEvent(window,"resize"));Blockly.highlightedConnection_&&(Blockly.highlightedConnection_.unhighlight(),Blockly.highlightedConnection_=null);Blockly.Css.setCursor(Blockly.Css.Cursor.OPEN)};Blockly.BlockSvg.prototype.showHelp_=function(){var a=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;a&&alert(a)};
Blockly.BlockSvg.prototype.showContextMenu_=function(a){if(!this.workspace.options.readOnly&&this.contextMenu){var b=this,c=[];if(this.isDeletable()&&this.isMovable()&&!b.isInFlyout){var d={text:Blockly.Msg.DUPLICATE_BLOCK,enabled:!0,callback:function(){Blockly.duplicate_(b)}};this.getDescendants().length>this.workspace.remainingCapacity()&&(d.enabled=!1);c.push(d);this.isEditable()&&this.workspace.options.comments&&(d={enabled:!goog.userAgent.IE},this.comment?(d.text=Blockly.Msg.REMOVE_COMMENT,d.callback=
function(){b.setCommentText(null)}):(d.text=Blockly.Msg.ADD_COMMENT,d.callback=function(){b.setCommentText("")}),c.push(d));var d=this.getDescendants().length,e=this.getNextBlock();e&&(d-=e.getDescendants().length);d={text:1==d?Blockly.Msg.DELETE_BLOCK:Blockly.Msg.DELETE_X_BLOCKS.replace("%1",String(d)),enabled:!0,callback:function(){b.dispose(!0,!0)}};c.push(d)}d={enabled:!(goog.isFunction(this.helpUrl)?!this.helpUrl():!this.helpUrl)};d.text=Blockly.Msg.HELP;d.callback=function(){b.showHelp_()};
c.push(d);this.customContextMenu&&!b.isInFlyout&&this.customContextMenu(c);Blockly.ContextMenu.show(a,c,this.RTL);Blockly.ContextMenu.currentBlock=this}};Blockly.BlockSvg.prototype.moveConnections_=function(a,b){if(this.rendered){for(var c=this.getConnections_(!1),d=0;d<c.length;d++)c[d].moveBy(a,b);c=this.getIcons();for(d=0;d<c.length;d++)c[d].computeIconLocation();for(d=0;d<this.childBlocks_.length;d++)this.childBlocks_[d].moveConnections_(a,b)}};
Blockly.BlockSvg.prototype.setDragging_=function(a){a?this.addDragging():this.removeDragging();for(var b=0;b<this.childBlocks_.length;b++)this.childBlocks_[b].setDragging_(a)};
Blockly.BlockSvg.prototype.onMouseMove_=function(a){if(!("mousemove"==a.type&&1>=a.clientX&&0==a.clientY&&0==a.button)){Blockly.removeAllRanges();var b=this.getRelativeToSurfaceXY(),c=this.workspace.moveDrag(a),d=this.getSvgRoot();1==Blockly.dragMode_&&goog.math.Coordinate.distance(b,c)*this.workspace.scale>Blockly.DRAG_RADIUS&&(Blockly.dragMode_=2,Blockly.longStop_(),d.translate_="",d.skew_="",this.parentBlock_&&(this.setParent(null),this.disconnectUiEffect()),this.setDragging_(!0),this.workspace.recordDeleteAreas());
if(2==Blockly.dragMode_){var e=b.x-this.dragStartXY_.x,b=b.y-this.dragStartXY_.y;d.translate_="translate("+c.x+","+c.y+")";d.setAttribute("transform",d.translate_+d.skew_);for(c=0;c<this.draggedBubbles_.length;c++)d=this.draggedBubbles_[c],d.bubble.setIconLocation(d.x+e,d.y+b);for(var d=this.getConnections_(!1),f=null,g=null,h=Blockly.SNAP_RADIUS,c=0;c<d.length;c++){var k=d[c],l=k.closest(h,e,b);l.connection&&(f=l.connection,g=k,h=l.radius)}Blockly.highlightedConnection_&&Blockly.highlightedConnection_!=
f&&(Blockly.highlightedConnection_.unhighlight(),Blockly.highlightedConnection_=null,Blockly.localConnection_=null);f&&f!=Blockly.highlightedConnection_&&(f.highlight(),Blockly.highlightedConnection_=f,Blockly.localConnection_=g);this.isDeletable()&&this.workspace.isDeleteArea(a)}}a.stopPropagation()};Blockly.BlockSvg.prototype.updateMovable=function(){this.isMovable()?Blockly.addClass_(this.svgGroup_,"blocklyDraggable"):Blockly.removeClass_(this.svgGroup_,"blocklyDraggable")};
Blockly.BlockSvg.prototype.setMovable=function(a){Blockly.BlockSvg.superClass_.setMovable.call(this,a);this.updateMovable()};Blockly.BlockSvg.prototype.setEditable=function(a){Blockly.BlockSvg.superClass_.setEditable.call(this,a);if(this.rendered)for(a=0;a<this.icons_.length;a++)this.icons_[a].updateEditable()};Blockly.BlockSvg.prototype.setShadow=function(a){Blockly.BlockSvg.superClass_.setShadow.call(this,a);this.updateColour()};Blockly.BlockSvg.prototype.getSvgRoot=function(){return this.svgGroup_};
Blockly.BlockSvg.SEP_SPACE_X=10;Blockly.BlockSvg.SEP_SPACE_Y=10;Blockly.BlockSvg.INLINE_PADDING_Y=5;Blockly.BlockSvg.MIN_BLOCK_Y=25;Blockly.BlockSvg.TAB_HEIGHT=20;Blockly.BlockSvg.TAB_WIDTH=8;Blockly.BlockSvg.NOTCH_WIDTH=30;Blockly.BlockSvg.CORNER_RADIUS=8;Blockly.BlockSvg.START_HAT=!1;Blockly.BlockSvg.START_HAT_PATH="c 30,-15 70,-15 100,0";Blockly.BlockSvg.START_HAT_HIGHLIGHT_LTR="c 17.8,-9.2 45.3,-14.9 75,-8.7 M 100.5,0.5";Blockly.BlockSvg.START_HAT_HIGHLIGHT_RTL="m 25,-8.7 c 29.7,-6.2 57.2,-0.5 75,8.7";
Blockly.BlockSvg.DISTANCE_45_INSIDE=(1-Math.SQRT1_2)*(Blockly.BlockSvg.CORNER_RADIUS-.5)+.5;Blockly.BlockSvg.DISTANCE_45_OUTSIDE=(1-Math.SQRT1_2)*(Blockly.BlockSvg.CORNER_RADIUS+.5)-.5;Blockly.BlockSvg.NOTCH_PATH_LEFT="l 6,4 3,0 6,-4";Blockly.BlockSvg.NOTCH_PATH_LEFT_HIGHLIGHT="l 6,4 3,0 6,-4";Blockly.BlockSvg.NOTCH_PATH_RIGHT="l -6,4 -3,0 -6,-4";Blockly.BlockSvg.JAGGED_TEETH="l 8,0 0,4 8,4 -16,8 8,4";Blockly.BlockSvg.JAGGED_TEETH_HEIGHT=20;Blockly.BlockSvg.JAGGED_TEETH_WIDTH=15;
Blockly.BlockSvg.TAB_PATH_DOWN="v 5 c 0,10 -"+Blockly.BlockSvg.TAB_WIDTH+",-8 -"+Blockly.BlockSvg.TAB_WIDTH+",7.5 s "+Blockly.BlockSvg.TAB_WIDTH+",-2.5 "+Blockly.BlockSvg.TAB_WIDTH+",7.5";Blockly.BlockSvg.TAB_PATH_DOWN_HIGHLIGHT_RTL="v 6.5 m -"+.97*Blockly.BlockSvg.TAB_WIDTH+",3 q -"+.05*Blockly.BlockSvg.TAB_WIDTH+",10 "+.3*Blockly.BlockSvg.TAB_WIDTH+",9.5 m "+.67*Blockly.BlockSvg.TAB_WIDTH+",-1.9 v 1.4";Blockly.BlockSvg.TOP_LEFT_CORNER_START="m 0,"+Blockly.BlockSvg.CORNER_RADIUS;
Blockly.BlockSvg.TOP_LEFT_CORNER_START_HIGHLIGHT_RTL="m "+Blockly.BlockSvg.DISTANCE_45_INSIDE+","+Blockly.BlockSvg.DISTANCE_45_INSIDE;Blockly.BlockSvg.TOP_LEFT_CORNER_START_HIGHLIGHT_LTR="m 0.5,"+(Blockly.BlockSvg.CORNER_RADIUS-.5);Blockly.BlockSvg.TOP_LEFT_CORNER="A "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,1 "+Blockly.BlockSvg.CORNER_RADIUS+",0";
Blockly.BlockSvg.TOP_LEFT_CORNER_HIGHLIGHT="A "+(Blockly.BlockSvg.CORNER_RADIUS-.5)+","+(Blockly.BlockSvg.CORNER_RADIUS-.5)+" 0 0,1 "+Blockly.BlockSvg.CORNER_RADIUS+",0.5";Blockly.BlockSvg.INNER_TOP_LEFT_CORNER=Blockly.BlockSvg.NOTCH_PATH_RIGHT+" h -"+(Blockly.BlockSvg.NOTCH_WIDTH-15-Blockly.BlockSvg.CORNER_RADIUS)+" h -0.5 a "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,0 -"+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS;
Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER="a "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,0 "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS;Blockly.BlockSvg.INNER_TOP_LEFT_CORNER_HIGHLIGHT_RTL="a "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,0 "+(-Blockly.BlockSvg.DISTANCE_45_OUTSIDE-.5)+","+(Blockly.BlockSvg.CORNER_RADIUS-Blockly.BlockSvg.DISTANCE_45_OUTSIDE);
Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER_HIGHLIGHT_RTL="a "+(Blockly.BlockSvg.CORNER_RADIUS+.5)+","+(Blockly.BlockSvg.CORNER_RADIUS+.5)+" 0 0,0 "+(Blockly.BlockSvg.CORNER_RADIUS+.5)+","+(Blockly.BlockSvg.CORNER_RADIUS+.5);Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER_HIGHLIGHT_LTR="a "+(Blockly.BlockSvg.CORNER_RADIUS+.5)+","+(Blockly.BlockSvg.CORNER_RADIUS+.5)+" 0 0,0 "+(Blockly.BlockSvg.CORNER_RADIUS-Blockly.BlockSvg.DISTANCE_45_OUTSIDE)+","+(Blockly.BlockSvg.DISTANCE_45_OUTSIDE+.5);
Blockly.BlockSvg.SEP_SPACE_X=10;Blockly.BlockSvg.SEP_SPACE_Y=10;Blockly.BlockSvg.INLINE_PADDING_Y=5;Blockly.BlockSvg.MIN_BLOCK_Y=25;Blockly.BlockSvg.TAB_HEIGHT=20;Blockly.BlockSvg.TAB_WIDTH=8;Blockly.BlockSvg.NOTCH_WIDTH=30;Blockly.BlockSvg.CORNER_RADIUS=4;Blockly.BlockSvg.START_HAT=!0;Blockly.BlockSvg.START_HAT_PATH="c 30,-15 70,-15 100,0";Blockly.BlockSvg.NOTCH_PATH_LEFT="l 6,4 3,0 6,-4";Blockly.BlockSvg.NOTCH_PATH_RIGHT="l -6,4 -3,0 -6,-4";
Blockly.BlockSvg.TAB_PATH_DOWN="v 5 c 0,10 -"+Blockly.BlockSvg.TAB_WIDTH+",-8 -"+Blockly.BlockSvg.TAB_WIDTH+",7.5 s "+Blockly.BlockSvg.TAB_WIDTH+",-2.5 "+Blockly.BlockSvg.TAB_WIDTH+",7.5";Blockly.BlockSvg.TOP_LEFT_CORNER_START="m 0,"+Blockly.BlockSvg.CORNER_RADIUS;Blockly.BlockSvg.TOP_LEFT_CORNER="A "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,1 "+Blockly.BlockSvg.CORNER_RADIUS+",0";
Blockly.BlockSvg.INNER_TOP_LEFT_CORNER=Blockly.BlockSvg.NOTCH_PATH_RIGHT+" h -"+(Blockly.BlockSvg.NOTCH_WIDTH-15-Blockly.BlockSvg.CORNER_RADIUS)+" h -0.5 a "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,0 -"+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS;Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER="a "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,0 "+Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS;
Blockly.BlockSvg.prototype.dispose=function(a,b,c){Blockly.Field.startCache();this.onchangeWrapper_&&(Blockly.unbindEvent_(this.onchangeWrapper_),this.onchangeWrapper_=null);Blockly.selected==this&&Blockly.terminateDrag_();Blockly.ContextMenu.currentBlock==this&&Blockly.ContextMenu.hide();b&&this.rendered&&(this.unplug(a,!1),this.disposeUiEffect());this.rendered=!1;b=this.getIcons();for(c=0;c<b.length;c++)b[c].dispose();Blockly.BlockSvg.superClass_.dispose.call(this,a);goog.dom.removeNode(this.svgGroup_);
this.svgPathDark_=this.svgPathLight_=this.svgPath_=this.svgGroup_=null;Blockly.Field.stopCache()};
Blockly.BlockSvg.prototype.disposeUiEffect=function(){this.workspace.playAudio("delete");var a=Blockly.getSvgXY_(this.svgGroup_,this.workspace),b=this.svgGroup_.cloneNode(!0);b.translateX_=a.x;b.translateY_=a.y;b.setAttribute("transform","translate("+b.translateX_+","+b.translateY_+")");this.workspace.getParentSvg().appendChild(b);b.bBox_=b.getBBox();Blockly.BlockSvg.disposeUiStep_(b,this.RTL,new Date,this.workspace.scale)};
this.svgPath_=this.svgGroup_=null;Blockly.Field.stopCache()};Blockly.BlockSvg.prototype.disposeUiEffect=function(){this.workspace.playAudio("delete");var a=Blockly.getSvgXY_(this.svgGroup_,this.workspace),b=this.svgGroup_.cloneNode(!0);b.translateX_=a.x;b.translateY_=a.y;b.setAttribute("transform","translate("+b.translateX_+","+b.translateY_+")");this.workspace.getParentSvg().appendChild(b);b.bBox_=b.getBBox();Blockly.BlockSvg.disposeUiStep_(b,this.RTL,new Date,this.workspace.scale)};
Blockly.BlockSvg.disposeUiStep_=function(a,b,c,d){var e=(new Date-c)/150;1<e?goog.dom.removeNode(a):(a.setAttribute("transform","translate("+(a.translateX_+(b?-1:1)*a.bBox_.width*d/2*e)+","+(a.translateY_+a.bBox_.height*d*e)+") scale("+(1-e)*d+")"),setTimeout(function(){Blockly.BlockSvg.disposeUiStep_(a,b,c,d)},10))};
Blockly.BlockSvg.prototype.connectionUiEffect=function(){this.workspace.playAudio("click");if(!(1>this.workspace.scale)){var a=Blockly.getSvgXY_(this.svgGroup_,this.workspace);this.outputConnection?(a.x+=(this.RTL?3:-3)*this.workspace.scale,a.y+=13*this.workspace.scale):this.previousConnection&&(a.x+=(this.RTL?-23:23)*this.workspace.scale,a.y+=3*this.workspace.scale);a=Blockly.createSvgElement("circle",{cx:a.x,cy:a.y,r:0,fill:"none",stroke:"#888","stroke-width":10},this.workspace.getParentSvg());
Blockly.BlockSvg.connectionUiStep_(a,new Date,this.workspace.scale)}};Blockly.BlockSvg.connectionUiStep_=function(a,b,c){var d=(new Date-b)/150;1<d?goog.dom.removeNode(a):(a.setAttribute("r",25*d*c),a.style.opacity=1-d,Blockly.BlockSvg.disconnectUiStop_.pid_=setTimeout(function(){Blockly.BlockSvg.connectionUiStep_(a,b,c)},10))};
Blockly.BlockSvg.prototype.disconnectUiEffect=function(){this.workspace.playAudio("disconnect");if(!(1>this.workspace.scale)){var a=this.getHeightWidth().height,a=Math.atan(10/a)/Math.PI*180;this.RTL||(a*=-1);Blockly.BlockSvg.disconnectUiStep_(this.svgGroup_,a,new Date)}};
Blockly.BlockSvg.disconnectUiStep_=function(a,b,c){var d=(new Date-c)/200;1<d?a.skew_="":(a.skew_="skewX("+Math.round(Math.sin(d*Math.PI*3)*(1-d)*b)+")",Blockly.BlockSvg.disconnectUiStop_.group=a,Blockly.BlockSvg.disconnectUiStop_.pid=setTimeout(function(){Blockly.BlockSvg.disconnectUiStep_(a,b,c)},10));a.setAttribute("transform",a.translate_+a.skew_)};
Blockly.BlockSvg.disconnectUiStop_=function(){if(Blockly.BlockSvg.disconnectUiStop_.group){clearTimeout(Blockly.BlockSvg.disconnectUiStop_.pid);var a=Blockly.BlockSvg.disconnectUiStop_.group;a.skew_="";a.setAttribute("transform",a.translate_);Blockly.BlockSvg.disconnectUiStop_.group=null}};Blockly.BlockSvg.disconnectUiStop_.pid=0;Blockly.BlockSvg.disconnectUiStop_.group=null;
Blockly.BlockSvg.prototype.updateColour=function(){if(!this.disabled){var a=this.getColour(),b=goog.color.hexToRgb(a);if(this.isShadow())b=goog.color.lighten(b,.6),a=goog.color.rgbArrayToHex(b),this.svgPathLight_.style.display="none",this.svgPathDark_.setAttribute("fill",a);else{this.svgPathLight_.style.display="";var c=goog.color.rgbArrayToHex(goog.color.lighten(b,.3)),b=goog.color.rgbArrayToHex(goog.color.darken(b,.2));this.svgPathLight_.setAttribute("stroke",c);this.svgPathDark_.setAttribute("fill",
b)}this.svgPath_.setAttribute("fill",a);a=this.getIcons();for(c=0;c<a.length;c++)a[c].updateColour();for(a=0;c=this.inputList[a];a++)for(var b=0,d;d=c.fieldRow[b];b++)d.setText(null)}};
Blockly.BlockSvg.prototype.updateDisabled=function(){var a=Blockly.hasClass_(this.svgGroup_,"blocklyDisabled");this.disabled||this.getInheritedDisabled()?a||(Blockly.addClass_(this.svgGroup_,"blocklyDisabled"),this.svgPath_.setAttribute("fill","url(#"+this.workspace.options.disabledPatternId+")")):a&&(Blockly.removeClass_(this.svgGroup_,"blocklyDisabled"),this.updateColour());for(var a=this.getChildren(),b=0,c;c=a[b];b++)c.updateDisabled()};
Blockly.BlockSvg.prototype.updateColour=function(){var a=this.getColour(),b=goog.color.hexToRgb(a);this.isShadow()&&(b=goog.color.lighten(b,.6),a=goog.color.rgbArrayToHex(b));this.svgPath_.setAttribute("fill",a);a=goog.color.darken(b,.1);a=goog.color.rgbArrayToHex(a);this.svgPath_.setAttribute("stroke",a);a=this.getIcons();for(b=0;b<a.length;b++)a[b].updateColour();for(a=0;b=this.inputList[a];a++)for(var c=0,d;d=b.fieldRow[c];c++)d.setText(null)};Blockly.BlockSvg.prototype.updateDisabled=function(){};
Blockly.BlockSvg.prototype.getCommentText=function(){return this.comment?this.comment.getText().replace(/\s+$/,"").replace(/ +\n/g,"\n"):""};Blockly.BlockSvg.prototype.setCommentText=function(a){var b=!1;goog.isString(a)?(this.comment||(this.comment=new Blockly.Comment(this),b=!0),this.comment.setText(a)):this.comment&&(this.comment.dispose(),b=!0);b&&this.rendered&&(this.render(),this.bumpNeighbours_())};
Blockly.BlockSvg.prototype.setWarningText=function(a,b){this.setWarningText.pid_||(this.setWarningText.pid_=Object.create(null));var c=b||"";if(c)this.setWarningText.pid_[c]&&(clearTimeout(this.setWarningText.pid_[c]),delete this.setWarningText.pid_[c]);else for(var d in this.setWarningText.pid_)clearTimeout(this.setWarningText.pid_[d]),delete this.setWarningText.pid_[d];if(2==Blockly.dragMode_){var e=this;this.setWarningText.pid_[c]=setTimeout(function(){e.workspace&&(delete e.setWarningText.pid_[c],
e.setWarningText(a,c))},100)}else{this.isInFlyout&&(a=null);d=this.getSurroundParent();for(var f=null;d;)d.isCollapsed()&&(f=d),d=d.getSurroundParent();f&&f.setWarningText(a,"collapsed "+this.id+" "+c);d=!1;goog.isString(a)?(this.warning||(this.warning=new Blockly.Warning(this),d=!0),this.warning.setText(a,c)):this.warning&&!c?(this.warning.dispose(),d=!0):this.warning&&(d=this.warning.getText(),this.warning.setText("",c),(f=this.warning.getText())||this.warning.dispose(),d=d==f);d&&this.rendered&&
(this.render(),this.bumpNeighbours_())}};Blockly.BlockSvg.prototype.setMutator=function(a){this.mutator&&this.mutator!==a&&this.mutator.dispose();a&&(a.block_=this,this.mutator=a,a.createIcon())};Blockly.BlockSvg.prototype.setDisabled=function(a){this.disabled!=a&&(Blockly.BlockSvg.superClass_.setDisabled.call(this,a),this.rendered&&this.updateDisabled(),this.workspace.fireChangeEvent())};Blockly.BlockSvg.prototype.addSelect=function(){Blockly.addClass_(this.svgGroup_,"blocklySelected");this.svgGroup_.parentNode.appendChild(this.svgGroup_)};
Blockly.BlockSvg.prototype.removeSelect=function(){Blockly.removeClass_(this.svgGroup_,"blocklySelected")};Blockly.BlockSvg.prototype.addDragging=function(){Blockly.addClass_(this.svgGroup_,"blocklyDragging")};Blockly.BlockSvg.prototype.removeDragging=function(){Blockly.removeClass_(this.svgGroup_,"blocklyDragging")};
e.setWarningText(a,c))},100)}else{this.isInFlyout&&(a=null);d=!1;if(goog.isString(a))this.warning||(this.warning=new Blockly.Warning(this),d=!0),this.warning.setText(a,c);else if(this.warning&&!c)this.warning.dispose(),d=!0;else if(this.warning){d=this.warning.getText();this.warning.setText("",c);var f=this.warning.getText();f||this.warning.dispose();d=d==f}d&&this.rendered&&(this.render(),this.bumpNeighbours_())}};
Blockly.BlockSvg.prototype.setMutator=function(a){this.mutator&&this.mutator!==a&&this.mutator.dispose();a&&(a.block_=this,this.mutator=a,a.createIcon())};Blockly.BlockSvg.prototype.addSelect=function(){Blockly.addClass_(this.svgGroup_,"blocklySelected");this.svgGroup_.parentNode.appendChild(this.svgGroup_)};Blockly.BlockSvg.prototype.removeSelect=function(){Blockly.removeClass_(this.svgGroup_,"blocklySelected")};Blockly.BlockSvg.prototype.addDragging=function(){Blockly.addClass_(this.svgGroup_,"blocklyDragging")};
Blockly.BlockSvg.prototype.removeDragging=function(){Blockly.removeClass_(this.svgGroup_,"blocklyDragging")};
Blockly.BlockSvg.prototype.render=function(a){Blockly.Field.startCache();this.rendered=!0;var b=Blockly.BlockSvg.SEP_SPACE_X;this.RTL&&(b=-b);for(var c=this.getIcons(),d=0;d<c.length;d++)b=c[d].renderIcon(b);b+=this.RTL?Blockly.BlockSvg.SEP_SPACE_X:-Blockly.BlockSvg.SEP_SPACE_X;c=this.renderCompute_(b);this.renderDraw_(b,c);!1!==a&&((a=this.getParent())?a.render(!0):Blockly.fireUiEvent(window,"resize"));Blockly.Field.stopCache()};
Blockly.BlockSvg.prototype.renderFields_=function(a,b,c){c+=Blockly.BlockSvg.INLINE_PADDING_Y;this.RTL&&(b=-b);for(var d=0,e;e=a[d];d++){var f=e.getSvgRoot();f&&(this.RTL?(b-=e.renderSep+e.renderWidth,f.setAttribute("transform","translate("+b+","+c+")"),e.renderWidth&&(b-=Blockly.BlockSvg.SEP_SPACE_X)):(f.setAttribute("transform","translate("+(b+e.renderSep)+","+c+")"),e.renderWidth&&(b+=e.renderSep+e.renderWidth+Blockly.BlockSvg.SEP_SPACE_X)))}return this.RTL?-b:b};
Blockly.BlockSvg.prototype.renderCompute_=function(a){var b=this.inputList,c=[];c.rightEdge=a+2*Blockly.BlockSvg.SEP_SPACE_X;if(this.previousConnection||this.nextConnection)c.rightEdge=Math.max(c.rightEdge,Blockly.BlockSvg.NOTCH_WIDTH+Blockly.BlockSvg.SEP_SPACE_X);for(var d=0,e=0,f=!1,g=!1,h=!1,k=void 0,l=this.getInputsInline()&&!this.isCollapsed(),q=0,m;m=b[q];q++)if(m.isVisible()){var p;l&&k&&k!=Blockly.NEXT_STATEMENT&&m.type!=Blockly.NEXT_STATEMENT?p=c[c.length-1]:(k=m.type,p=[],p.type=l&&m.type!=
Blockly.NEXT_STATEMENT?Blockly.BlockSvg.INLINE:m.type,p.height=0,c.push(p));p.push(m);m.renderHeight=Blockly.BlockSvg.MIN_BLOCK_Y;m.renderWidth=l&&m.type==Blockly.INPUT_VALUE?Blockly.BlockSvg.TAB_WIDTH+1.25*Blockly.BlockSvg.SEP_SPACE_X:0;if(m.connection&&m.connection.targetConnection){var n=m.connection.targetBlock().getHeightWidth();m.renderHeight=Math.max(m.renderHeight,n.height);m.renderWidth=Math.max(m.renderWidth,n.width)}l||q!=b.length-1?!l&&m.type==Blockly.INPUT_VALUE&&b[q+1]&&b[q+1].type==
Blockly.NEXT_STATEMENT&&m.renderHeight--:m.renderHeight--;p.height=Math.max(p.height,m.renderHeight);m.fieldWidth=0;1==c.length&&(m.fieldWidth+=this.RTL?-a:a);for(var n=!1,r=0,t;t=m.fieldRow[r];r++){0!=r&&(m.fieldWidth+=Blockly.BlockSvg.SEP_SPACE_X);var u=t.getSize();t.renderWidth=u.width;t.renderSep=n&&t.EDITABLE?Blockly.BlockSvg.SEP_SPACE_X:0;m.fieldWidth+=t.renderWidth+t.renderSep;p.height=Math.max(p.height,u.height);n=t.EDITABLE}p.type!=Blockly.BlockSvg.INLINE&&(p.type==Blockly.NEXT_STATEMENT?
(g=!0,e=Math.max(e,m.fieldWidth)):(p.type==Blockly.INPUT_VALUE?f=!0:p.type==Blockly.DUMMY_INPUT&&(h=!0),d=Math.max(d,m.fieldWidth)))}for(a=0;p=c[a];a++)if(p.thicker=!1,p.type==Blockly.BlockSvg.INLINE)for(b=0;m=p[b];b++)if(m.type==Blockly.INPUT_VALUE){p.height+=2*Blockly.BlockSvg.INLINE_PADDING_Y;p.thicker=!0;break}c.statementEdge=2*Blockly.BlockSvg.SEP_SPACE_X+e;g&&(c.rightEdge=Math.max(c.rightEdge,c.statementEdge+Blockly.BlockSvg.NOTCH_WIDTH));f?c.rightEdge=Math.max(c.rightEdge,d+2*Blockly.BlockSvg.SEP_SPACE_X+
Blockly.BlockSvg.TAB_WIDTH):h&&(c.rightEdge=Math.max(c.rightEdge,d+2*Blockly.BlockSvg.SEP_SPACE_X));c.hasValue=f;c.hasStatement=g;c.hasDummy=h;return c};
Blockly.BlockSvg.prototype.renderCompute_=function(a){var b=this.inputList,c=[];c.rightEdge=a+2*Blockly.BlockSvg.SEP_SPACE_X;if(this.previousConnection||this.nextConnection)c.rightEdge=Math.max(c.rightEdge,Blockly.BlockSvg.NOTCH_WIDTH+Blockly.BlockSvg.SEP_SPACE_X);for(var d=0,e=0,f=!1,g=!1,h=!1,k=void 0,l=0,m;m=b[l];l++)if(m.isVisible()){var n;k&&k!=Blockly.NEXT_STATEMENT&&m.type!=Blockly.NEXT_STATEMENT?n=c[c.length-1]:(k=m.type,n=[],n.type=m.type!=Blockly.NEXT_STATEMENT?Blockly.BlockSvg.INLINE:m.type,
n.height=0,c.push(n));n.push(m);m.renderHeight=Blockly.BlockSvg.MIN_BLOCK_Y;m.renderWidth=m.type==Blockly.INPUT_VALUE?Blockly.BlockSvg.TAB_WIDTH+1.25*Blockly.BlockSvg.SEP_SPACE_X:0;if(m.connection&&m.connection.targetConnection){var q=m.connection.targetBlock().getHeightWidth();m.renderHeight=Math.max(m.renderHeight,q.height);m.renderWidth=Math.max(m.renderWidth,q.width)}l==b.length-1?m.renderHeight--:m.type==Blockly.INPUT_VALUE&&b[l+1]&&b[l+1].type==Blockly.NEXT_STATEMENT&&m.renderHeight--;n.height=
Math.max(n.height,m.renderHeight);m.fieldWidth=0;1==c.length&&(m.fieldWidth+=this.RTL?-a:a);for(var q=!1,p=0,r;r=m.fieldRow[p];p++){0!=p&&(m.fieldWidth+=Blockly.BlockSvg.SEP_SPACE_X);var t=r.getSize();r.renderWidth=t.width;r.renderSep=q&&r.EDITABLE?Blockly.BlockSvg.SEP_SPACE_X:0;m.fieldWidth+=r.renderWidth+r.renderSep;n.height=Math.max(n.height,t.height);q=r.EDITABLE}n.type!=Blockly.BlockSvg.INLINE&&(n.type==Blockly.NEXT_STATEMENT?(g=!0,e=Math.max(e,m.fieldWidth)):(n.type==Blockly.INPUT_VALUE?f=!0:
n.type==Blockly.DUMMY_INPUT&&(h=!0),d=Math.max(d,m.fieldWidth)))}for(a=0;n=c[a];a++)if(n.thicker=!1,n.type==Blockly.BlockSvg.INLINE)for(b=0;m=n[b];b++)if(m.type==Blockly.INPUT_VALUE){n.height+=2*Blockly.BlockSvg.INLINE_PADDING_Y;n.thicker=!0;break}c.statementEdge=2*Blockly.BlockSvg.SEP_SPACE_X+e;g&&(c.rightEdge=Math.max(c.rightEdge,c.statementEdge+Blockly.BlockSvg.NOTCH_WIDTH));f?c.rightEdge=Math.max(c.rightEdge,d+2*Blockly.BlockSvg.SEP_SPACE_X+Blockly.BlockSvg.TAB_WIDTH):h&&(c.rightEdge=Math.max(c.rightEdge,
d+2*Blockly.BlockSvg.SEP_SPACE_X));c.hasValue=f;c.hasStatement=g;c.hasDummy=h;return c};
Blockly.BlockSvg.prototype.renderDraw_=function(a,b){this.startHat_=!1;if(this.outputConnection)this.squareBottomLeftCorner_=this.squareTopLeftCorner_=!0;else{this.squareBottomLeftCorner_=this.squareTopLeftCorner_=!1;if(this.previousConnection){var c=this.previousConnection.targetBlock();c&&c.getNextBlock()==this&&(this.squareTopLeftCorner_=!0)}else Blockly.BlockSvg.START_HAT&&(this.startHat_=this.squareTopLeftCorner_=!0,b.rightEdge=Math.max(b.rightEdge,100));this.getNextBlock()&&(this.squareBottomLeftCorner_=
!0)}var d=this.getRelativeToSurfaceXY(),e=[],f=[],c=[],g=[];this.renderDrawTop_(e,c,d,b.rightEdge);var h=this.renderDrawRight_(e,c,f,g,d,b,a);this.renderDrawBottom_(e,c,d,h);this.renderDrawLeft_(e,c,d,h);d=e.join(" ")+"\n"+f.join(" ");this.svgPath_.setAttribute("d",d);this.svgPathDark_.setAttribute("d",d);d=c.join(" ")+"\n"+g.join(" ");this.svgPathLight_.setAttribute("d",d);this.RTL&&(this.svgPath_.setAttribute("transform","scale(-1 1)"),this.svgPathLight_.setAttribute("transform","scale(-1 1)"),
this.svgPathDark_.setAttribute("transform","translate(1,1) scale(-1 1)"))};
Blockly.BlockSvg.prototype.renderDrawTop_=function(a,b,c,d){this.squareTopLeftCorner_?(a.push("m 0,0"),b.push("m 0.5,0.5"),this.startHat_&&(a.push(Blockly.BlockSvg.START_HAT_PATH),b.push(this.RTL?Blockly.BlockSvg.START_HAT_HIGHLIGHT_RTL:Blockly.BlockSvg.START_HAT_HIGHLIGHT_LTR))):(a.push(Blockly.BlockSvg.TOP_LEFT_CORNER_START),b.push(this.RTL?Blockly.BlockSvg.TOP_LEFT_CORNER_START_HIGHLIGHT_RTL:Blockly.BlockSvg.TOP_LEFT_CORNER_START_HIGHLIGHT_LTR),a.push(Blockly.BlockSvg.TOP_LEFT_CORNER),b.push(Blockly.BlockSvg.TOP_LEFT_CORNER_HIGHLIGHT));
this.previousConnection&&(a.push("H",Blockly.BlockSvg.NOTCH_WIDTH-15),b.push("H",Blockly.BlockSvg.NOTCH_WIDTH-15),a.push(Blockly.BlockSvg.NOTCH_PATH_LEFT),b.push(Blockly.BlockSvg.NOTCH_PATH_LEFT_HIGHLIGHT),this.previousConnection.moveTo(c.x+(this.RTL?-Blockly.BlockSvg.NOTCH_WIDTH:Blockly.BlockSvg.NOTCH_WIDTH),c.y));a.push("H",d);b.push("H",d-.5);this.width=d};
Blockly.BlockSvg.prototype.renderDrawRight_=function(a,b,c,d,e,f,g){for(var h,k=0,l,q,m=0,p;p=f[m];m++){h=Blockly.BlockSvg.SEP_SPACE_X;0==m&&(h+=this.RTL?-g:g);b.push("M",f.rightEdge-.5+","+(k+.5));if(this.isCollapsed()){var n=p[0];l=k;this.renderFields_(n.fieldRow,h,l);a.push(Blockly.BlockSvg.JAGGED_TEETH);b.push("h 8");n=p.height-Blockly.BlockSvg.JAGGED_TEETH_HEIGHT;a.push("v",n);this.RTL&&(b.push("v 3.9 l 7.2,3.4 m -14.5,8.9 l 7.3,3.5"),b.push("v",n-.7));this.width+=Blockly.BlockSvg.JAGGED_TEETH_WIDTH}else if(p.type==
Blockly.BlockSvg.INLINE){for(var r=0;n=p[r];r++)l=k,p.thicker&&(l+=Blockly.BlockSvg.INLINE_PADDING_Y),h=this.renderFields_(n.fieldRow,h,l),n.type!=Blockly.DUMMY_INPUT&&(h+=n.renderWidth+Blockly.BlockSvg.SEP_SPACE_X),n.type==Blockly.INPUT_VALUE&&(c.push("M",h-Blockly.BlockSvg.SEP_SPACE_X+","+(k+Blockly.BlockSvg.INLINE_PADDING_Y)),c.push("h",Blockly.BlockSvg.TAB_WIDTH-2-n.renderWidth),c.push(Blockly.BlockSvg.TAB_PATH_DOWN),c.push("v",n.renderHeight+1-Blockly.BlockSvg.TAB_HEIGHT),c.push("h",n.renderWidth+
2-Blockly.BlockSvg.TAB_WIDTH),c.push("z"),this.RTL?(d.push("M",h-Blockly.BlockSvg.SEP_SPACE_X-2.5+Blockly.BlockSvg.TAB_WIDTH-n.renderWidth+","+(k+Blockly.BlockSvg.INLINE_PADDING_Y+.5)),d.push(Blockly.BlockSvg.TAB_PATH_DOWN_HIGHLIGHT_RTL),d.push("v",n.renderHeight-Blockly.BlockSvg.TAB_HEIGHT+2.5),d.push("h",n.renderWidth-Blockly.BlockSvg.TAB_WIDTH+2)):(d.push("M",h-Blockly.BlockSvg.SEP_SPACE_X+.5+","+(k+Blockly.BlockSvg.INLINE_PADDING_Y+.5)),d.push("v",n.renderHeight+1),d.push("h",Blockly.BlockSvg.TAB_WIDTH-
2-n.renderWidth),d.push("M",h-n.renderWidth-Blockly.BlockSvg.SEP_SPACE_X+.9+","+(k+Blockly.BlockSvg.INLINE_PADDING_Y+Blockly.BlockSvg.TAB_HEIGHT-.7)),d.push("l",.46*Blockly.BlockSvg.TAB_WIDTH+",-2.1")),l=this.RTL?e.x-h-Blockly.BlockSvg.TAB_WIDTH+Blockly.BlockSvg.SEP_SPACE_X+n.renderWidth+1:e.x+h+Blockly.BlockSvg.TAB_WIDTH-Blockly.BlockSvg.SEP_SPACE_X-n.renderWidth-1,q=e.y+k+Blockly.BlockSvg.INLINE_PADDING_Y+1,n.connection.moveTo(l,q),n.connection.targetConnection&&n.connection.tighten_());h=Math.max(h,
f.rightEdge);this.width=Math.max(this.width,h);a.push("H",h);b.push("H",h-.5);a.push("v",p.height);this.RTL&&b.push("v",p.height-1)}else p.type==Blockly.INPUT_VALUE?(n=p[0],l=k,n.align!=Blockly.ALIGN_LEFT&&(r=f.rightEdge-n.fieldWidth-Blockly.BlockSvg.TAB_WIDTH-2*Blockly.BlockSvg.SEP_SPACE_X,n.align==Blockly.ALIGN_RIGHT?h+=r:n.align==Blockly.ALIGN_CENTRE&&(h+=r/2)),this.renderFields_(n.fieldRow,h,l),a.push(Blockly.BlockSvg.TAB_PATH_DOWN),r=p.height-Blockly.BlockSvg.TAB_HEIGHT,a.push("v",r),this.RTL?
(b.push(Blockly.BlockSvg.TAB_PATH_DOWN_HIGHLIGHT_RTL),b.push("v",r+.5)):(b.push("M",f.rightEdge-5+","+(k+Blockly.BlockSvg.TAB_HEIGHT-.7)),b.push("l",.46*Blockly.BlockSvg.TAB_WIDTH+",-2.1")),l=e.x+(this.RTL?-f.rightEdge-1:f.rightEdge+1),q=e.y+k,n.connection.moveTo(l,q),n.connection.targetConnection&&(n.connection.tighten_(),this.width=Math.max(this.width,f.rightEdge+n.connection.targetBlock().getHeightWidth().width-Blockly.BlockSvg.TAB_WIDTH+1))):p.type==Blockly.DUMMY_INPUT?(n=p[0],l=k,n.align!=Blockly.ALIGN_LEFT&&
(r=f.rightEdge-n.fieldWidth-2*Blockly.BlockSvg.SEP_SPACE_X,f.hasValue&&(r-=Blockly.BlockSvg.TAB_WIDTH),n.align==Blockly.ALIGN_RIGHT?h+=r:n.align==Blockly.ALIGN_CENTRE&&(h+=r/2)),this.renderFields_(n.fieldRow,h,l),a.push("v",p.height),this.RTL&&b.push("v",p.height-1)):p.type==Blockly.NEXT_STATEMENT&&(n=p[0],0==m&&(a.push("v",Blockly.BlockSvg.SEP_SPACE_Y),this.RTL&&b.push("v",Blockly.BlockSvg.SEP_SPACE_Y-1),k+=Blockly.BlockSvg.SEP_SPACE_Y),l=k,n.align!=Blockly.ALIGN_LEFT&&(r=f.statementEdge-n.fieldWidth-
2*Blockly.BlockSvg.SEP_SPACE_X,n.align==Blockly.ALIGN_RIGHT?h+=r:n.align==Blockly.ALIGN_CENTRE&&(h+=r/2)),this.renderFields_(n.fieldRow,h,l),h=f.statementEdge+Blockly.BlockSvg.NOTCH_WIDTH,a.push("H",h),a.push(Blockly.BlockSvg.INNER_TOP_LEFT_CORNER),a.push("v",p.height-2*Blockly.BlockSvg.CORNER_RADIUS),a.push(Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER),a.push("H",f.rightEdge),this.RTL?(b.push("M",h-Blockly.BlockSvg.NOTCH_WIDTH+Blockly.BlockSvg.DISTANCE_45_OUTSIDE+","+(k+Blockly.BlockSvg.DISTANCE_45_OUTSIDE)),
b.push(Blockly.BlockSvg.INNER_TOP_LEFT_CORNER_HIGHLIGHT_RTL),b.push("v",p.height-2*Blockly.BlockSvg.CORNER_RADIUS),b.push(Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER_HIGHLIGHT_RTL)):(b.push("M",h-Blockly.BlockSvg.NOTCH_WIDTH+Blockly.BlockSvg.DISTANCE_45_OUTSIDE+","+(k+p.height-Blockly.BlockSvg.DISTANCE_45_OUTSIDE)),b.push(Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER_HIGHLIGHT_LTR)),b.push("H",f.rightEdge-.5),l=e.x+(this.RTL?-h:h+1),q=e.y+k+1,n.connection.moveTo(l,q),n.connection.targetConnection&&(n.connection.tighten_(),
this.width=Math.max(this.width,f.statementEdge+n.connection.targetBlock().getHeightWidth().width)),m==f.length-1||f[m+1].type==Blockly.NEXT_STATEMENT)&&(a.push("v",Blockly.BlockSvg.SEP_SPACE_Y),this.RTL&&b.push("v",Blockly.BlockSvg.SEP_SPACE_Y-1),k+=Blockly.BlockSvg.SEP_SPACE_Y);k+=p.height}f.length||(k=Blockly.BlockSvg.MIN_BLOCK_Y,a.push("V",k),this.RTL&&b.push("V",k-1));return k};
Blockly.BlockSvg.prototype.renderDrawBottom_=function(a,b,c,d){this.height=d+1;this.nextConnection&&(a.push("H",Blockly.BlockSvg.NOTCH_WIDTH+(this.RTL?.5:-.5)+" "+Blockly.BlockSvg.NOTCH_PATH_RIGHT),this.nextConnection.moveTo(this.RTL?c.x-Blockly.BlockSvg.NOTCH_WIDTH:c.x+Blockly.BlockSvg.NOTCH_WIDTH,c.y+d+1),this.nextConnection.targetConnection&&this.nextConnection.tighten_(),this.height+=4);this.squareBottomLeftCorner_?(a.push("H 0"),this.RTL||b.push("M","0.5,"+(d-.5))):(a.push("H",Blockly.BlockSvg.CORNER_RADIUS),
a.push("a",Blockly.BlockSvg.CORNER_RADIUS+","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,1 -"+Blockly.BlockSvg.CORNER_RADIUS+",-"+Blockly.BlockSvg.CORNER_RADIUS),this.RTL||(b.push("M",Blockly.BlockSvg.DISTANCE_45_INSIDE+","+(d-Blockly.BlockSvg.DISTANCE_45_INSIDE)),b.push("A",Blockly.BlockSvg.CORNER_RADIUS-.5+","+(Blockly.BlockSvg.CORNER_RADIUS-.5)+" 0 0,1 0.5,"+(d-Blockly.BlockSvg.CORNER_RADIUS))))};
Blockly.BlockSvg.prototype.renderDrawLeft_=function(a,b,c,d){this.outputConnection?(this.outputConnection.moveTo(c.x,c.y),a.push("V",Blockly.BlockSvg.TAB_HEIGHT),a.push("c 0,-10 -"+Blockly.BlockSvg.TAB_WIDTH+",8 -"+Blockly.BlockSvg.TAB_WIDTH+",-7.5 s "+Blockly.BlockSvg.TAB_WIDTH+",2.5 "+Blockly.BlockSvg.TAB_WIDTH+",-7.5"),this.RTL?(b.push("M",-.25*Blockly.BlockSvg.TAB_WIDTH+",8.4"),b.push("l",-.45*Blockly.BlockSvg.TAB_WIDTH+",-2.1")):(b.push("V",Blockly.BlockSvg.TAB_HEIGHT-1.5),b.push("m",-.92*Blockly.BlockSvg.TAB_WIDTH+
",-0.5 q "+-.19*Blockly.BlockSvg.TAB_WIDTH+",-5.5 0,-11"),b.push("m",.92*Blockly.BlockSvg.TAB_WIDTH+",1 V 0.5 H 1")),this.width+=Blockly.BlockSvg.TAB_WIDTH):this.RTL||(this.squareTopLeftCorner_?b.push("V",.5):b.push("V",Blockly.BlockSvg.CORNER_RADIUS));a.push("z")};Blockly.Msg={};goog.getMsgOrig=goog.getMsg;goog.getMsg=function(a,b){var c=goog.getMsg.blocklyMsgMap[a];c&&(a=Blockly.Msg[c]);return goog.getMsgOrig(a,b)};goog.getMsg.blocklyMsgMap={Today:"TODAY"};Blockly.FieldTextInput=function(a,b){Blockly.FieldTextInput.superClass_.constructor.call(this,a);this.setChangeHandler(b)};goog.inherits(Blockly.FieldTextInput,Blockly.Field);Blockly.FieldTextInput.FONTSIZE=11;Blockly.FieldTextInput.prototype.CURSOR="text";Blockly.FieldTextInput.prototype.spellcheck_=!0;Blockly.FieldTextInput.prototype.dispose=function(){Blockly.WidgetDiv.hideIfOwner(this);Blockly.FieldTextInput.superClass_.dispose.call(this)};
!0)}var c=this.getRelativeToSurfaceXY(),d=[];this.renderDrawTop_(d,c,b.rightEdge);var e=this.renderDrawRight_(d,c,b,a);this.renderDrawBottom_(d,c,e);this.renderDrawLeft_(d,c,e);c=d.join(" ");this.svgPath_.setAttribute("d",c);this.RTL&&this.svgPath_.setAttribute("transform","scale(-1 1)")};
Blockly.BlockSvg.prototype.renderDrawTop_=function(a,b,c){this.squareTopLeftCorner_?(a.push("m 0,0"),this.startHat_&&a.push(Blockly.BlockSvg.START_HAT_PATH)):(a.push(Blockly.BlockSvg.TOP_LEFT_CORNER_START),a.push(Blockly.BlockSvg.TOP_LEFT_CORNER));this.previousConnection&&(a.push("H",Blockly.BlockSvg.NOTCH_WIDTH-15),a.push(Blockly.BlockSvg.NOTCH_PATH_LEFT),this.previousConnection.moveTo(b.x+(this.RTL?-Blockly.BlockSvg.NOTCH_WIDTH:Blockly.BlockSvg.NOTCH_WIDTH),b.y));a.push("H",c);this.width=c};
Blockly.BlockSvg.prototype.renderDrawRight_=function(a,b,c,d){for(var e,f=0,g,h,k=0,l;l=c[k];k++){e=Blockly.BlockSvg.SEP_SPACE_X;0==k&&(e+=this.RTL?-d:d);if(l.type==Blockly.BlockSvg.INLINE){for(var m=0,n;n=l[m];m++)g=f,l.thicker&&(g+=Blockly.BlockSvg.INLINE_PADDING_Y),e=this.renderFields_(n.fieldRow,e,g),n.type!=Blockly.DUMMY_INPUT&&(e+=n.renderWidth+Blockly.BlockSvg.SEP_SPACE_X),n.type==Blockly.INPUT_VALUE&&(g=this.RTL?b.x-e-Blockly.BlockSvg.TAB_WIDTH+Blockly.BlockSvg.SEP_SPACE_X+n.renderWidth+1:
b.x+e+Blockly.BlockSvg.TAB_WIDTH-Blockly.BlockSvg.SEP_SPACE_X-n.renderWidth-1,h=b.y+f+Blockly.BlockSvg.INLINE_PADDING_Y+1,n.connection.moveTo(g,h),n.connection.targetConnection&&n.connection.tighten_());e=Math.max(e,c.rightEdge);this.width=Math.max(this.width,e);a.push("H",e);a.push("v",l.height)}else l.type==Blockly.DUMMY_INPUT?(n=l[0],g=f,n.align!=Blockly.ALIGN_LEFT&&(m=c.rightEdge-n.fieldWidth-2*Blockly.BlockSvg.SEP_SPACE_X,c.hasValue&&(m-=Blockly.BlockSvg.TAB_WIDTH),n.align==Blockly.ALIGN_RIGHT?
e+=m:n.align==Blockly.ALIGN_CENTRE&&(e+=m/2)),this.renderFields_(n.fieldRow,e,g),a.push("v",l.height)):l.type==Blockly.NEXT_STATEMENT&&(n=l[0],0==k&&(a.push("v",Blockly.BlockSvg.SEP_SPACE_Y),f+=Blockly.BlockSvg.SEP_SPACE_Y),g=f,n.align!=Blockly.ALIGN_LEFT&&(m=c.statementEdge-n.fieldWidth-2*Blockly.BlockSvg.SEP_SPACE_X,n.align==Blockly.ALIGN_RIGHT?e+=m:n.align==Blockly.ALIGN_CENTRE&&(e+=m/2)),this.renderFields_(n.fieldRow,e,g),e=c.statementEdge+Blockly.BlockSvg.NOTCH_WIDTH,a.push("H",e),a.push(Blockly.BlockSvg.INNER_TOP_LEFT_CORNER),
a.push("v",l.height-2*Blockly.BlockSvg.CORNER_RADIUS),a.push(Blockly.BlockSvg.INNER_BOTTOM_LEFT_CORNER),a.push("H",c.rightEdge),g=b.x+(this.RTL?-e:e+1),h=b.y+f+1,n.connection.moveTo(g,h),n.connection.targetConnection&&(n.connection.tighten_(),this.width=Math.max(this.width,c.statementEdge+n.connection.targetBlock().getHeightWidth().width)),k==c.length-1||c[k+1].type==Blockly.NEXT_STATEMENT)&&(a.push("v",Blockly.BlockSvg.SEP_SPACE_Y),f+=Blockly.BlockSvg.SEP_SPACE_Y);f+=l.height}c.length||(f=Blockly.BlockSvg.MIN_BLOCK_Y,
a.push("V",f));return f};
Blockly.BlockSvg.prototype.renderDrawBottom_=function(a,b,c){this.height=c+1;this.nextConnection&&(a.push("H",Blockly.BlockSvg.NOTCH_WIDTH+(this.RTL?.5:-.5)+" "+Blockly.BlockSvg.NOTCH_PATH_RIGHT),this.nextConnection.moveTo(this.RTL?b.x-Blockly.BlockSvg.NOTCH_WIDTH:b.x+Blockly.BlockSvg.NOTCH_WIDTH,b.y+c+1),this.nextConnection.targetConnection&&this.nextConnection.tighten_(),this.height+=4);this.squareBottomLeftCorner_?a.push("H 0"):(a.push("H",Blockly.BlockSvg.CORNER_RADIUS),a.push("a",Blockly.BlockSvg.CORNER_RADIUS+
","+Blockly.BlockSvg.CORNER_RADIUS+" 0 0,1 -"+Blockly.BlockSvg.CORNER_RADIUS+",-"+Blockly.BlockSvg.CORNER_RADIUS))};
Blockly.BlockSvg.prototype.renderDrawLeft_=function(a,b,c){this.outputConnection&&(this.outputConnection.moveTo(b.x,b.y),this.outputConnection.getOutputShape()===Blockly.Connection.NUMBER&&(a.push("V",Blockly.BlockSvg.TAB_HEIGHT),a.push("c 0,-10 -"+Blockly.BlockSvg.TAB_WIDTH+",8 -"+Blockly.BlockSvg.TAB_WIDTH+",-7.5 s "+Blockly.BlockSvg.TAB_WIDTH+",2.5 "+Blockly.BlockSvg.TAB_WIDTH+",-7.5"),this.width+=Blockly.BlockSvg.TAB_WIDTH));a.push("z")};Blockly.Msg={};goog.getMsgOrig=goog.getMsg;goog.getMsg=function(a,b){var c=goog.getMsg.blocklyMsgMap[a];c&&(a=Blockly.Msg[c]);return goog.getMsgOrig(a,b)};goog.getMsg.blocklyMsgMap={Today:"TODAY"};Blockly.FieldTextInput=function(a,b){Blockly.FieldTextInput.superClass_.constructor.call(this,a);this.setChangeHandler(b)};goog.inherits(Blockly.FieldTextInput,Blockly.Field);Blockly.FieldTextInput.FONTSIZE=11;Blockly.FieldTextInput.prototype.CURSOR="text";Blockly.FieldTextInput.prototype.spellcheck_=!0;Blockly.FieldTextInput.prototype.dispose=function(){Blockly.WidgetDiv.hideIfOwner(this);Blockly.FieldTextInput.superClass_.dispose.call(this)};
Blockly.FieldTextInput.prototype.setText=function(a){if(null!==a){if(this.sourceBlock_&&this.changeHandler_){var b=this.changeHandler_(a);null!==b&&void 0!==b&&(a=b)}Blockly.Field.prototype.setText.call(this,a)}};Blockly.FieldTextInput.prototype.setSpellcheck=function(a){this.spellcheck_=a};
Blockly.FieldTextInput.prototype.showEditor_=function(a){var b=a||!1;if(!b&&(goog.userAgent.MOBILE||goog.userAgent.ANDROID||goog.userAgent.IPAD))a=window.prompt(Blockly.Msg.CHANGE_VALUE_TITLE,this.text_),this.sourceBlock_&&this.changeHandler_&&(b=this.changeHandler_(a),void 0!==b&&(a=b)),null!==a&&this.setText(a);else{Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,this.widgetDispose_());var c=Blockly.WidgetDiv.DIV;a=goog.dom.createDom("input","blocklyHtmlInput");a.setAttribute("spellcheck",this.spellcheck_);
var d=Blockly.FieldTextInput.FONTSIZE*this.sourceBlock_.workspace.scale+"pt";c.style.fontSize=d;a.style.fontSize=d;Blockly.FieldTextInput.htmlInput_=a;c.appendChild(a);a.value=a.defaultValue=this.text_;a.oldValue_=null;this.validate_();this.resizeEditor_();b||(a.focus(),a.select());a.onKeyDownWrapper_=Blockly.bindEvent_(a,"keydown",this,this.onHtmlInputKeyDown_);a.onKeyUpWrapper_=Blockly.bindEvent_(a,"keyup",this,this.onHtmlInputChange_);a.onKeyPressWrapper_=Blockly.bindEvent_(a,"keypress",this,this.onHtmlInputChange_);
b=this.sourceBlock_.workspace.getCanvas();a.onWorkspaceChangeWrapper_=Blockly.bindEvent_(b,"blocklyWorkspaceChange",this,this.resizeEditor_)}};Blockly.FieldTextInput.prototype.onHtmlInputKeyDown_=function(a){var b=Blockly.FieldTextInput.htmlInput_;13==a.keyCode?Blockly.WidgetDiv.hide():27==a.keyCode?(this.setText(b.defaultValue),Blockly.WidgetDiv.hide()):9==a.keyCode&&(Blockly.WidgetDiv.hide(),this.sourceBlock_.tab(this,!a.shiftKey),a.preventDefault())};
Blockly.FieldTextInput.prototype.onHtmlInputChange_=function(a){var b=Blockly.FieldTextInput.htmlInput_;27!=a.keyCode&&(a=b.value,a!==b.oldValue_?(this.sourceBlock_.setShadow(!1),b.oldValue_=a,this.setText(a),this.validate_()):goog.userAgent.WEBKIT&&this.sourceBlock_.render())};
Blockly.FieldTextInput.prototype.onHtmlInputChange_=function(a){var b=Blockly.FieldTextInput.htmlInput_;27!=a.keyCode&&(a=b.value,a!==b.oldValue_?(b.oldValue_=a,this.setText(a),this.validate_()):goog.userAgent.WEBKIT&&this.sourceBlock_.render())};
Blockly.FieldTextInput.prototype.validate_=function(){var a=!0;goog.asserts.assertObject(Blockly.FieldTextInput.htmlInput_);var b=Blockly.FieldTextInput.htmlInput_;this.sourceBlock_&&this.changeHandler_&&(a=this.changeHandler_(b.value));null===a?Blockly.addClass_(b,"blocklyInvalidInput"):Blockly.removeClass_(b,"blocklyInvalidInput")};
Blockly.FieldTextInput.prototype.resizeEditor_=function(){var a=Blockly.WidgetDiv.DIV,b=this.fieldGroup_.getBBox();a.style.width=b.width*this.sourceBlock_.workspace.scale+"px";a.style.height=b.height*this.sourceBlock_.workspace.scale+"px";b=this.getAbsoluteXY_();if(this.sourceBlock_.RTL){var c=this.getScaledBBox_();b.x+=c.width;b.x-=a.offsetWidth}b.y+=1;goog.userAgent.GECKO&&Blockly.WidgetDiv.DIV.style.top&&(--b.x,--b.y);goog.userAgent.WEBKIT&&(b.y-=3);a.style.left=b.x+"px";a.style.top=b.y+"px"};
Blockly.FieldTextInput.prototype.widgetDispose_=function(){var a=this;return function(){var b=Blockly.FieldTextInput.htmlInput_,c=b.value;if(a.sourceBlock_&&a.changeHandler_){var d=a.changeHandler_(c);null===d?c=b.defaultValue:void 0!==d&&(c=d)}a.setText(c);a.sourceBlock_.rendered&&a.sourceBlock_.render();Blockly.unbindEvent_(b.onKeyDownWrapper_);Blockly.unbindEvent_(b.onKeyUpWrapper_);Blockly.unbindEvent_(b.onKeyPressWrapper_);Blockly.unbindEvent_(b.onWorkspaceChangeWrapper_);Blockly.FieldTextInput.htmlInput_=
@ -1174,11 +1157,11 @@ d.y=d.y+f.height+e.height>=b.height+c.y?d.y-(f.height-1):d.y+(e.height-1);this.s
void 0!==b&&(a=b)}null!==a&&(g.sourceBlock_.setShadow(!1),g.setValue(a))})};Blockly.FieldColour.widgetDispose_=function(){Blockly.FieldColour.changeEventKey_&&goog.events.unlistenByKey(Blockly.FieldColour.changeEventKey_)};Blockly.FieldDropdown=function(a,b){this.menuGenerator_=a;this.setChangeHandler(b);this.trimOptions_();var c=this.getOptions_()[0];this.value_=c[1];Blockly.FieldDropdown.superClass_.constructor.call(this,c[0])};goog.inherits(Blockly.FieldDropdown,Blockly.Field);Blockly.FieldDropdown.CHECKMARK_OVERHANG=25;Blockly.FieldDropdown.ARROW_CHAR=goog.userAgent.ANDROID?"\u25bc":"\u25be";Blockly.FieldDropdown.prototype.CURSOR="default";
Blockly.FieldDropdown.prototype.init=function(a){this.sourceBlock_||(this.arrow_=Blockly.createSvgElement("tspan",{},null),this.arrow_.appendChild(document.createTextNode(a.RTL?Blockly.FieldDropdown.ARROW_CHAR+" ":" "+Blockly.FieldDropdown.ARROW_CHAR)),Blockly.FieldDropdown.superClass_.init.call(this,a),a=this.text_,this.text_=null,this.setText(a))};
Blockly.FieldDropdown.prototype.showEditor_=function(){Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,null);var a=this,b=new goog.ui.Menu;b.setRightToLeft(this.sourceBlock_.RTL);for(var c=this.getOptions_(),d=0;d<c.length;d++){var e=c[d][1],f=new goog.ui.MenuItem(c[d][0]);f.setRightToLeft(this.sourceBlock_.RTL);f.setValue(e);f.setCheckable(!0);b.addChild(f,!0);f.setChecked(e==this.value_)}goog.events.listen(b,goog.ui.Component.EventType.ACTION,function(b){if(b=b.target){b=b.getValue();if(a.sourceBlock_&&
a.changeHandler_){var c=a.changeHandler_(b);void 0!==c&&(b=c)}null!==b&&(a.sourceBlock_.setShadow(!1),a.setValue(b))}Blockly.WidgetDiv.hideIfOwner(a)});b.getHandler().listen(b.getElement(),goog.events.EventType.TOUCHSTART,function(a){this.getOwnerControl(a.target).handleMouseDown(a)});b.getHandler().listen(b.getElement(),goog.events.EventType.TOUCHEND,function(a){this.getOwnerControl(a.target).performActionInternal(a)});c=goog.dom.getViewportSize();d=goog.style.getViewportPageOffset(document);e=this.getAbsoluteXY_();
f=this.getScaledBBox_();b.render(Blockly.WidgetDiv.DIV);var g=b.getElement();Blockly.addClass_(g,"blocklyDropdownMenu");var h=goog.style.getSize(g);h.height=g.scrollHeight;e.y=e.y+h.height+f.height>=c.height+d.y?e.y-(h.height+2):e.y+f.height;this.sourceBlock_.RTL?(e.x+=f.width,e.x+=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e.x<d.x+h.width&&(e.x=d.x+h.width)):(e.x-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e.x>c.width+d.x-h.width&&(e.x=c.width+d.x-h.width));Blockly.WidgetDiv.position(e.x,e.y,c,d,this.sourceBlock_.RTL);
b.setAllowAutoFocus(!0);g.focus()};
Blockly.FieldDropdown.prototype.trimOptions_=function(){this.suffixField=this.prefixField=null;var a=this.menuGenerator_;if(goog.isArray(a)&&!(2>a.length)){var b=a.map(function(a){return a[0]}),c=Blockly.shortestStringLength(b),d=Blockly.commonWordPrefix(b,c),e=Blockly.commonWordSuffix(b,c);if((d||e)&&!(c<=d+e)){d&&(this.prefixField=b[0].substring(0,d-1));e&&(this.suffixField=b[0].substr(1-e));b=[];for(c=0;c<a.length;c++){var f=a[c][0],g=a[c][1],f=f.substring(d,f.length-e);b[c]=[f,g]}this.menuGenerator_=
b}}};Blockly.FieldDropdown.prototype.getOptions_=function(){return goog.isFunction(this.menuGenerator_)?this.menuGenerator_.call(this):this.menuGenerator_};Blockly.FieldDropdown.prototype.getValue=function(){return this.value_};Blockly.FieldDropdown.prototype.setValue=function(a){this.value_=a;for(var b=this.getOptions_(),c=0;c<b.length;c++)if(b[c][1]==a){this.setText(b[c][0]);return}this.setText(a)};
a.changeHandler_){var c=a.changeHandler_(b);void 0!==c&&(b=c)}null!==b&&a.setValue(b)}Blockly.WidgetDiv.hideIfOwner(a)});b.getHandler().listen(b.getElement(),goog.events.EventType.TOUCHSTART,function(a){this.getOwnerControl(a.target).handleMouseDown(a)});b.getHandler().listen(b.getElement(),goog.events.EventType.TOUCHEND,function(a){this.getOwnerControl(a.target).performActionInternal(a)});c=goog.dom.getViewportSize();d=goog.style.getViewportPageOffset(document);e=this.getAbsoluteXY_();f=this.getScaledBBox_();
b.render(Blockly.WidgetDiv.DIV);var g=b.getElement();Blockly.addClass_(g,"blocklyDropdownMenu");var h=goog.style.getSize(g);h.height=g.scrollHeight;e.y=e.y+h.height+f.height>=c.height+d.y?e.y-(h.height+2):e.y+f.height;this.sourceBlock_.RTL?(e.x+=f.width,e.x+=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e.x<d.x+h.width&&(e.x=d.x+h.width)):(e.x-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e.x>c.width+d.x-h.width&&(e.x=c.width+d.x-h.width));Blockly.WidgetDiv.position(e.x,e.y,c,d,this.sourceBlock_.RTL);b.setAllowAutoFocus(!0);
g.focus()};
Blockly.FieldDropdown.prototype.trimOptions_=function(){this.suffixField=this.prefixField=null;var a=this.menuGenerator_;if(goog.isArray(a)&&!(2>a.length)){var b=a.map(function(a){return a[0]}),c=Blockly.shortestStringLength(b),d=Blockly.commonWordPrefix(b,c),e=Blockly.commonWordSuffix(b,c);if((d||e)&&!(c<=d+e)){d&&(this.prefixField=b[0].substring(0,d-1));e&&(this.suffixField=b[0].substr(1-e));b=[];for(c=0;c<a.length;c++){var f=a[c][0],g=a[c][1],f=f.substring(d,f.length-e);b[c]=[f,g]}this.menuGenerator_=b}}};
Blockly.FieldDropdown.prototype.getOptions_=function(){return goog.isFunction(this.menuGenerator_)?this.menuGenerator_.call(this):this.menuGenerator_};Blockly.FieldDropdown.prototype.getValue=function(){return this.value_};Blockly.FieldDropdown.prototype.setValue=function(a){this.value_=a;for(var b=this.getOptions_(),c=0;c<b.length;c++)if(b[c][1]==a){this.setText(b[c][0]);return}this.setText(a)};
Blockly.FieldDropdown.prototype.setText=function(a){this.sourceBlock_&&this.arrow_&&(this.arrow_.style.fill=this.sourceBlock_.getColour());null!==a&&a!==this.text_&&(this.text_=a,this.updateTextNode_(),this.textElement_&&(this.sourceBlock_.RTL?this.textElement_.insertBefore(this.arrow_,this.textElement_.firstChild):this.textElement_.appendChild(this.arrow_)),this.sourceBlock_&&this.sourceBlock_.rendered&&(this.sourceBlock_.render(),this.sourceBlock_.bumpNeighbours_(),this.sourceBlock_.workspace.fireChangeEvent()))};
Blockly.FieldDropdown.prototype.dispose=function(){Blockly.WidgetDiv.hideIfOwner(this);Blockly.FieldDropdown.superClass_.dispose.call(this)};Blockly.FieldImage=function(a,b,c,d){this.sourceBlock_=null;this.height_=Number(c);this.width_=Number(b);this.size_=new goog.math.Size(this.width_,this.height_+2*Blockly.BlockSvg.INLINE_PADDING_Y);this.text_=d||"";this.setValue(a)};goog.inherits(Blockly.FieldImage,Blockly.Field);Blockly.FieldImage.prototype.rectElement_=null;Blockly.FieldImage.prototype.EDITABLE=!1;
Blockly.FieldImage.prototype.init=function(a){this.sourceBlock_||(this.sourceBlock_=a,this.fieldGroup_=Blockly.createSvgElement("g",{},null),this.visible_||(this.fieldGroup_.style.display="none"),this.imageElement_=Blockly.createSvgElement("image",{height:this.height_+"px",width:this.width_+"px"},this.fieldGroup_),this.setValue(this.src_),goog.userAgent.GECKO&&(this.rectElement_=Blockly.createSvgElement("rect",{height:this.height_+"px",width:this.width_+"px","fill-opacity":0},this.fieldGroup_)),a.getSvgRoot().appendChild(this.fieldGroup_),
@ -1203,7 +1186,7 @@ Blockly.Names.prototype.getName=function(a,b){var c=a.toLowerCase()+"_"+b,d=b==B
Blockly.Names.prototype.safeName_=function(a){a?(a=encodeURI(a.replace(/ /g,"_")).replace(/[^\w]/g,"_"),-1!="0123456789".indexOf(a[0])&&(a="my_"+a)):a="unnamed";return a};Blockly.Names.equals=function(a,b){return a.toLowerCase()==b.toLowerCase()};Blockly.Procedures={};Blockly.Procedures.NAME_TYPE="PROCEDURE";Blockly.Procedures.allProcedures=function(a){a=a.getAllBlocks();for(var b=[],c=[],d=0;d<a.length;d++)if(a[d].getProcedureDef){var e=a[d].getProcedureDef();e&&(e[2]?b.push(e):c.push(e))}c.sort(Blockly.Procedures.procTupleComparator_);b.sort(Blockly.Procedures.procTupleComparator_);return[c,b]};Blockly.Procedures.procTupleComparator_=function(a,b){return a[0].toLowerCase().localeCompare(b[0].toLowerCase())};
Blockly.Procedures.findLegalName=function(a,b){if(b.isInFlyout)return a;for(;!Blockly.Procedures.isLegalName(a,b.workspace,b);){var c=a.match(/^(.*?)(\d+)$/);a=c?c[1]+(parseInt(c[2],10)+1):a+"2"}return a};Blockly.Procedures.isLegalName=function(a,b,c){b=b.getAllBlocks();for(var d=0;d<b.length;d++)if(b[d]!=c&&b[d].getProcedureDef){var e=b[d].getProcedureDef();if(Blockly.Names.equals(e[0],a))return!1}return!0};
Blockly.Procedures.rename=function(a){a=a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");a=Blockly.Procedures.findLegalName(a,this.sourceBlock_);for(var b=this.sourceBlock_.workspace.getAllBlocks(),c=0;c<b.length;c++)b[c].renameProcedure&&b[c].renameProcedure(this.text_,a);return a};
Blockly.Procedures.flyoutCategory=function(a){function b(a,b){for(var d=0;d<a.length;d++){var h=a[d][0],k=a[d][1],l=goog.dom.createDom("block");l.setAttribute("type",b);l.setAttribute("gap",16);var q=goog.dom.createDom("mutation");q.setAttribute("name",h);l.appendChild(q);for(h=0;h<k.length;h++){var m=goog.dom.createDom("arg");m.setAttribute("name",k[h]);q.appendChild(m)}c.push(l)}}var c=[];if(Blockly.Blocks.procedures_defnoreturn){var d=goog.dom.createDom("block");d.setAttribute("type","procedures_defnoreturn");
Blockly.Procedures.flyoutCategory=function(a){function b(a,b){for(var d=0;d<a.length;d++){var h=a[d][0],k=a[d][1],l=goog.dom.createDom("block");l.setAttribute("type",b);l.setAttribute("gap",16);var m=goog.dom.createDom("mutation");m.setAttribute("name",h);l.appendChild(m);for(h=0;h<k.length;h++){var n=goog.dom.createDom("arg");n.setAttribute("name",k[h]);m.appendChild(n)}c.push(l)}}var c=[];if(Blockly.Blocks.procedures_defnoreturn){var d=goog.dom.createDom("block");d.setAttribute("type","procedures_defnoreturn");
d.setAttribute("gap",16);c.push(d)}Blockly.Blocks.procedures_defreturn&&(d=goog.dom.createDom("block"),d.setAttribute("type","procedures_defreturn"),d.setAttribute("gap",16),c.push(d));Blockly.Blocks.procedures_ifreturn&&(d=goog.dom.createDom("block"),d.setAttribute("type","procedures_ifreturn"),d.setAttribute("gap",16),c.push(d));c.length&&c[c.length-1].setAttribute("gap",24);a=Blockly.Procedures.allProcedures(a);b(a[0],"procedures_callnoreturn");b(a[1],"procedures_callreturn");return c};
Blockly.Procedures.getCallers=function(a,b){for(var c=[],d=b.getAllBlocks(),e=0;e<d.length;e++)if(d[e].getProcedureCall){var f=d[e].getProcedureCall();f&&Blockly.Names.equals(f,a)&&c.push(d[e])}return c};Blockly.Procedures.disposeCallers=function(a,b){for(var c=Blockly.Procedures.getCallers(a,b),d=0;d<c.length;d++)c[d].dispose(!0,!1)};Blockly.Procedures.mutateCallers=function(a,b,c,d){a=Blockly.Procedures.getCallers(a,b);for(b=0;b<a.length;b++)a[b].setProcedureParameters(c,d)};
Blockly.Procedures.getDefinition=function(a,b){for(var c=b.getAllBlocks(),d=0;d<c.length;d++)if(c[d].getProcedureDef){var e=c[d].getProcedureDef();if(e&&Blockly.Names.equals(e[0],a))return c[d]}return null};Blockly.Flyout=function(a){a.getMetrics=this.getMetrics_.bind(this);a.setMetrics=this.setMetrics_.bind(this);this.workspace_=new Blockly.WorkspaceSvg(a);this.workspace_.isFlyout=!0;this.RTL=!!a.RTL;this.eventWrappers_=[];this.buttons_=[];this.listeners_=[]};Blockly.Flyout.prototype.autoClose=!0;Blockly.Flyout.prototype.CORNER_RADIUS=8;Blockly.Flyout.prototype.SCROLLBAR_PADDING=2;Blockly.Flyout.prototype.width_=0;Blockly.Flyout.prototype.height_=0;
@ -1248,36 +1231,35 @@ Blockly.Toolbox.TreeSeparator.CONFIG_={cssTreeRow:"blocklyTreeSeparator"};Blockl
Blockly.Css.inject=function(a,b){if(!Blockly.Css.styleSheet_){var c=".blocklyDraggable {}\n";a&&(c+=Blockly.Css.CONTENT.join("\n"),Blockly.FieldDate&&(c+=Blockly.FieldDate.CSS.join("\n")));Blockly.Css.mediaPath_=b.replace(/[\\\/]$/,"");var c=c.replace(/<<<PATH>>>/g,Blockly.Css.mediaPath_),d=document.createElement("style");document.head.appendChild(d);c=document.createTextNode(c);d.appendChild(c);Blockly.Css.styleSheet_=d.sheet;Blockly.Css.setCursor(Blockly.Css.Cursor.OPEN)}};
Blockly.Css.setCursor=function(a){if(Blockly.Css.currentCursor_!=a){Blockly.Css.currentCursor_=a;var b="url("+Blockly.Css.mediaPath_+"/"+a+".cur), auto",c=".blocklyDraggable {\n cursor: "+b+";\n}\n";Blockly.Css.styleSheet_.deleteRule(0);Blockly.Css.styleSheet_.insertRule(c,0);for(var c=document.getElementsByClassName("blocklyToolboxDiv"),d=0,e;e=c[d];d++)e.style.cursor=a==Blockly.Css.Cursor.DELETE?b:"";document.body.parentNode.style.cursor=a==Blockly.Css.Cursor.OPEN?"":b}};
Blockly.Css.CONTENT=[".blocklySvg {","background-color: #fff;","outline: none;","overflow: hidden;","}",".blocklyWidgetDiv {","display: none;","position: absolute;","z-index: 999;","}",".blocklyTooltipDiv {","background-color: #ffffc7;","border: 1px solid #ddc;","box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15);","color: #000;","display: none;","font-family: sans-serif;","font-size: 9pt;","opacity: 0.9;","padding: 2px;","position: absolute;","z-index: 1000;","}",".blocklyResizeSE {","cursor: se-resize;",
"fill: #aaa;","}",".blocklyResizeSW {","cursor: sw-resize;","fill: #aaa;","}",".blocklyResizeLine {","stroke: #888;","stroke-width: 1;","}",".blocklyHighlightedConnectionPath {","fill: none;","stroke: #fc3;","stroke-width: 4px;","}",".blocklyPathLight {","fill: none;","stroke-linecap: round;","stroke-width: 1;","}",".blocklySelected>.blocklyPath {","stroke: #fc3;","stroke-width: 3px;","}",".blocklySelected>.blocklyPathLight {","display: none;","}",".blocklyDragging>.blocklyPath,",".blocklyDragging>.blocklyPathLight {",
"fill-opacity: .8;","stroke-opacity: .8;","}",".blocklyDragging>.blocklyPathDark {","display: none;","}",".blocklyDisabled>.blocklyPath {","fill-opacity: .5;","stroke-opacity: .5;","}",".blocklyDisabled>.blocklyPathLight,",".blocklyDisabled>.blocklyPathDark {","display: none;","}",".blocklyText {","cursor: default;","fill: #fff;","font-family: sans-serif;","font-size: 11pt;","}",".blocklyNonEditableText>text {","pointer-events: none;","}",".blocklyNonEditableText>rect,",".blocklyEditableText>rect {",
"fill: #fff;","fill-opacity: .6;","}",".blocklyNonEditableText>text,",".blocklyEditableText>text {","fill: #000;","}",".blocklyEditableText:hover>rect {","stroke: #fff;","stroke-width: 2;","}",".blocklyBubbleText {","fill: #000;","}",".blocklySvg text {","user-select: none;","-moz-user-select: none;","-webkit-user-select: none;","cursor: inherit;","}",".blocklyHidden {","display: none;","}",".blocklyFieldDropdown:not(.blocklyHidden) {","display: block;","}",".blocklyIconGroup {","cursor: default;",
"}",".blocklyIconGroup:not(:hover),",".blocklyIconGroupReadonly {","opacity: .6;","}",".blocklyIconShape {","fill: #00f;","stroke: #fff;","stroke-width: 1px;","}",".blocklyIconSymbol {","fill: #fff;","}",".blocklyMinimalBody {","margin: 0;","padding: 0;","}",".blocklyCommentTextarea {","background-color: #ffc;","border: 0;","margin: 0;","padding: 2px;","resize: none;","}",".blocklyHtmlInput {","border: none;","border-radius: 4px;","font-family: sans-serif;","height: 100%;","margin: 0;","outline: none;",
"padding: 0 1px;","width: 100%","}",".blocklyMainBackground {","stroke-width: 1;","stroke: #c6c6c6;","}",".blocklyMutatorBackground {","fill: #fff;","stroke: #ddd;","stroke-width: 1;","}",".blocklyFlyoutBackground {","fill: #ddd;","fill-opacity: .8;","}",".blocklyScrollbarBackground {","opacity: 0;","}",".blocklyScrollbarKnob {","fill: #ccc;","}",".blocklyScrollbarBackground:hover+.blocklyScrollbarKnob,",".blocklyScrollbarKnob:hover {","fill: #bbb;","}",".blocklyZoom>image {","opacity: .4;","}",".blocklyZoom>image:hover {",
"opacity: .6;","}",".blocklyZoom>image:active {","opacity: .8;","}",".blocklyFlyout .blocklyScrollbarKnob {","fill: #bbb;","}",".blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarKnob,",".blocklyFlyout .blocklyScrollbarKnob:hover {","fill: #aaa;","}",".blocklyInvalidInput {","background: #faa;","}",".blocklyAngleCircle {","stroke: #444;","stroke-width: 1;","fill: #ddd;","fill-opacity: .8;","}",".blocklyAngleMarks {","stroke: #444;","stroke-width: 1;","}",".blocklyAngleGauge {","fill: #f88;",
"fill-opacity: .8;","}",".blocklyAngleLine {","stroke: #f00;","stroke-width: 2;","stroke-linecap: round;","}",".blocklyContextMenu {","border-radius: 4px;","}",".blocklyDropdownMenu {","padding: 0 !important;","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon {","background: url(<<<PATH>>>/sprites.png) no-repeat -48px -16px !important;","}",".blocklyToolboxDiv {","background-color: #ddd;","overflow-x: visible;","overflow-y: auto;",
"position: absolute;","}",".blocklyTreeRoot {","padding: 4px 0;","}",".blocklyTreeRoot:focus {","outline: none;","}",".blocklyTreeRow {","height: 22px;","line-height: 22px;","margin-bottom: 3px;","padding-right: 8px;","white-space: nowrap;","}",'.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow {',"margin-left: 8px;","}",".blocklyTreeRow:not(.blocklyTreeSelected):hover {","background-color: #e4e4e4;","}",".blocklyTreeSeparator {","border-bottom: solid #e5e5e5 1px;","height: 0px;","margin: 5px 0;","}",
".blocklyTreeIcon {","background-image: url(<<<PATH>>>/sprites.png);","height: 16px;","vertical-align: middle;","width: 16px;","}",".blocklyTreeIconClosedLtr {","background-position: -32px -1px;","}",".blocklyTreeIconClosedRtl {","background-position: 0px -1px;","}",".blocklyTreeIconOpen {","background-position: -16px -1px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedLtr {","background-position: -32px -17px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedRtl {","background-position: 0px -17px;",
"}",".blocklyTreeSelected>.blocklyTreeIconOpen {","background-position: -16px -17px;","}",".blocklyTreeIconNone,",".blocklyTreeSelected>.blocklyTreeIconNone {","background-position: -48px -1px;","}",".blocklyTreeLabel {","cursor: default;","font-family: sans-serif;","font-size: 16px;","padding: 0 3px;","vertical-align: middle;","}",".blocklyTreeSelected .blocklyTreeLabel {","color: #fff;","}",".blocklyWidgetDiv .goog-palette {","outline: none;","cursor: default;","}",".blocklyWidgetDiv .goog-palette-table {",
"border: 1px solid #666;","border-collapse: collapse;","}",".blocklyWidgetDiv .goog-palette-cell {","height: 13px;","width: 15px;","margin: 0;","border: 0;","text-align: center;","vertical-align: middle;","border-right: 1px solid #666;","font-size: 1px;","}",".blocklyWidgetDiv .goog-palette-colorswatch {","position: relative;","height: 13px;","width: 15px;","border: 1px solid #666;","}",".blocklyWidgetDiv .goog-palette-cell-hover .goog-palette-colorswatch {","border: 1px solid #FFF;","}",".blocklyWidgetDiv .goog-palette-cell-selected .goog-palette-colorswatch {",
"border: 1px solid #000;","color: #fff;","}",".blocklyWidgetDiv .goog-menu {","background: #fff;","border-color: #ccc #666 #666 #ccc;","border-style: solid;","border-width: 1px;","cursor: default;","font: normal 13px Arial, sans-serif;","margin: 0;","outline: none;","padding: 4px 0;","position: absolute;","overflow-y: auto;","overflow-x: hidden;","max-height: 100%;","z-index: 20000;","}",".blocklyWidgetDiv .goog-menuitem {","color: #000;","font: normal 13px Arial, sans-serif;","list-style: none;",
"margin: 0;","padding: 4px 7em 4px 28px;","white-space: nowrap;","}",".blocklyWidgetDiv .goog-menuitem.goog-menuitem-rtl {","padding-left: 7em;","padding-right: 28px;","}",".blocklyWidgetDiv .goog-menu-nocheckbox .goog-menuitem,",".blocklyWidgetDiv .goog-menu-noicon .goog-menuitem {","padding-left: 12px;","}",".blocklyWidgetDiv .goog-menu-noaccel .goog-menuitem {","padding-right: 20px;","}",".blocklyWidgetDiv .goog-menuitem-content {","color: #000;","font: normal 13px Arial, sans-serif;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-accel,",
".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-content {","color: #ccc !important;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-icon {","opacity: 0.3;","-moz-opacity: 0.3;","filter: alpha(opacity=30);","}",".blocklyWidgetDiv .goog-menuitem-highlight,",".blocklyWidgetDiv .goog-menuitem-hover {","background-color: #d6e9f8;","border-color: #d6e9f8;","border-style: dotted;","border-width: 1px 0;","padding-bottom: 3px;","padding-top: 3px;","}",".blocklyWidgetDiv .goog-menuitem-checkbox,",
".blocklyWidgetDiv .goog-menuitem-icon {","background-repeat: no-repeat;","height: 16px;","left: 6px;","position: absolute;","right: auto;","vertical-align: middle;","width: 16px;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-icon {","left: auto;","right: 6px;","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon {","background: url(//ssl.gstatic.com/editor/editortoolbar.png) no-repeat -512px 0;",
"}",".blocklyWidgetDiv .goog-menuitem-accel {","color: #999;","direction: ltr;","left: auto;","padding: 0 6px;","position: absolute;","right: 0;","text-align: right;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-accel {","left: 0;","right: auto;","text-align: left;","}",".blocklyWidgetDiv .goog-menuitem-mnemonic-hint {","text-decoration: underline;","}",".blocklyWidgetDiv .goog-menuitem-mnemonic-separator {","color: #999;","font-size: 12px;","padding-left: 4px;","}",".blocklyWidgetDiv .goog-menuseparator {",
"border-top: 1px solid #ccc;","margin: 4px 0;","padding: 0;","}",""];Blockly.WidgetDiv={};Blockly.WidgetDiv.DIV=null;Blockly.WidgetDiv.owner_=null;Blockly.WidgetDiv.dispose_=null;Blockly.WidgetDiv.createDom=function(){Blockly.WidgetDiv.DIV||(Blockly.WidgetDiv.DIV=goog.dom.createDom("div","blocklyWidgetDiv"),document.body.appendChild(Blockly.WidgetDiv.DIV))};
"fill: #aaa;","}",".blocklyResizeSW {","cursor: sw-resize;","fill: #aaa;","}",".blocklyResizeLine {","stroke: #888;","stroke-width: 1;","}",".blocklyHighlightedConnectionPath {","fill: none;","stroke: #fc3;","stroke-width: 4px;","}",".blocklyPath {","stroke-width: 1px;","}",".blocklySelected>.blocklyPath {","stroke: #fc3;","stroke-width: 3px;","}",".blocklyDragging>.blocklyPath {","fill-opacity: .8;","stroke-opacity: .8;","}",".blocklyDisabled>.blocklyPath {","fill-opacity: .5;","stroke-opacity: .5;",
"}",".blocklyText {","cursor: default;","fill: #fff;","font-family: sans-serif;","font-size: 11pt;","}",".blocklyNonEditableText>text {","pointer-events: none;","}",".blocklyNonEditableText>rect,",".blocklyEditableText>rect {","fill: #fff;","fill-opacity: .6;","}",".blocklyNonEditableText>text,",".blocklyEditableText>text {","fill: #000;","}",".blocklyEditableText:hover>rect {","stroke: #fff;","stroke-width: 2;","}",".blocklyBubbleText {","fill: #000;","}",".blocklySvg text {","user-select: none;",
"-moz-user-select: none;","-webkit-user-select: none;","cursor: inherit;","}",".blocklyHidden {","display: none;","}",".blocklyFieldDropdown:not(.blocklyHidden) {","display: block;","}",".blocklyIconGroup {","cursor: default;","}",".blocklyIconGroup:not(:hover),",".blocklyIconGroupReadonly {","opacity: .6;","}",".blocklyIconShape {","fill: #00f;","stroke: #fff;","stroke-width: 1px;","}",".blocklyIconSymbol {","fill: #fff;","}",".blocklyMinimalBody {","margin: 0;","padding: 0;","}",".blocklyCommentTextarea {",
"background-color: #ffc;","border: 0;","margin: 0;","padding: 2px;","resize: none;","}",".blocklyHtmlInput {","border: none;","border-radius: 4px;","font-family: sans-serif;","height: 100%;","margin: 0;","outline: none;","padding: 0 1px;","width: 100%","}",".blocklyMainBackground {","stroke-width: 1;","stroke: #c6c6c6;","}",".blocklyMutatorBackground {","fill: #fff;","stroke: #ddd;","stroke-width: 1;","}",".blocklyFlyoutBackground {","fill: #ddd;","fill-opacity: .8;","}",".blocklyScrollbarBackground {",
"opacity: 0;","}",".blocklyScrollbarKnob {","fill: #ccc;","}",".blocklyScrollbarBackground:hover+.blocklyScrollbarKnob,",".blocklyScrollbarKnob:hover {","fill: #bbb;","}",".blocklyZoom>image {","opacity: .4;","}",".blocklyZoom>image:hover {","opacity: .6;","}",".blocklyZoom>image:active {","opacity: .8;","}",".blocklyFlyout .blocklyScrollbarKnob {","fill: #bbb;","}",".blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarKnob,",".blocklyFlyout .blocklyScrollbarKnob:hover {","fill: #aaa;",
"}",".blocklyInvalidInput {","background: #faa;","}",".blocklyAngleCircle {","stroke: #444;","stroke-width: 1;","fill: #ddd;","fill-opacity: .8;","}",".blocklyAngleMarks {","stroke: #444;","stroke-width: 1;","}",".blocklyAngleGauge {","fill: #f88;","fill-opacity: .8;","}",".blocklyAngleLine {","stroke: #f00;","stroke-width: 2;","stroke-linecap: round;","}",".blocklyContextMenu {","border-radius: 4px;","}",".blocklyDropdownMenu {","padding: 0 !important;","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",
".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon {","background: url(<<<PATH>>>/sprites.png) no-repeat -48px -16px !important;","}",".blocklyToolboxDiv {","background-color: #ddd;","overflow-x: visible;","overflow-y: auto;","position: absolute;","}",".blocklyTreeRoot {","padding: 4px 0;","}",".blocklyTreeRoot:focus {","outline: none;","}",".blocklyTreeRow {","height: 22px;","line-height: 22px;","margin-bottom: 3px;","padding-right: 8px;","white-space: nowrap;","}",'.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow {',
"margin-left: 8px;","}",".blocklyTreeRow:not(.blocklyTreeSelected):hover {","background-color: #e4e4e4;","}",".blocklyTreeSeparator {","border-bottom: solid #e5e5e5 1px;","height: 0px;","margin: 5px 0;","}",".blocklyTreeIcon {","background-image: url(<<<PATH>>>/sprites.png);","height: 16px;","vertical-align: middle;","width: 16px;","}",".blocklyTreeIconClosedLtr {","background-position: -32px -1px;","}",".blocklyTreeIconClosedRtl {","background-position: 0px -1px;","}",".blocklyTreeIconOpen {","background-position: -16px -1px;",
"}",".blocklyTreeSelected>.blocklyTreeIconClosedLtr {","background-position: -32px -17px;","}",".blocklyTreeSelected>.blocklyTreeIconClosedRtl {","background-position: 0px -17px;","}",".blocklyTreeSelected>.blocklyTreeIconOpen {","background-position: -16px -17px;","}",".blocklyTreeIconNone,",".blocklyTreeSelected>.blocklyTreeIconNone {","background-position: -48px -1px;","}",".blocklyTreeLabel {","cursor: default;","font-family: sans-serif;","font-size: 16px;","padding: 0 3px;","vertical-align: middle;",
"}",".blocklyTreeSelected .blocklyTreeLabel {","color: #fff;","}",".blocklyWidgetDiv .goog-palette {","outline: none;","cursor: default;","}",".blocklyWidgetDiv .goog-palette-table {","border: 1px solid #666;","border-collapse: collapse;","}",".blocklyWidgetDiv .goog-palette-cell {","height: 13px;","width: 15px;","margin: 0;","border: 0;","text-align: center;","vertical-align: middle;","border-right: 1px solid #666;","font-size: 1px;","}",".blocklyWidgetDiv .goog-palette-colorswatch {","position: relative;",
"height: 13px;","width: 15px;","border: 1px solid #666;","}",".blocklyWidgetDiv .goog-palette-cell-hover .goog-palette-colorswatch {","border: 1px solid #FFF;","}",".blocklyWidgetDiv .goog-palette-cell-selected .goog-palette-colorswatch {","border: 1px solid #000;","color: #fff;","}",".blocklyWidgetDiv .goog-menu {","background: #fff;","border-color: #ccc #666 #666 #ccc;","border-style: solid;","border-width: 1px;","cursor: default;","font: normal 13px Arial, sans-serif;","margin: 0;","outline: none;",
"padding: 4px 0;","position: absolute;","overflow-y: auto;","overflow-x: hidden;","max-height: 100%;","z-index: 20000;","}",".blocklyWidgetDiv .goog-menuitem {","color: #000;","font: normal 13px Arial, sans-serif;","list-style: none;","margin: 0;","padding: 4px 7em 4px 28px;","white-space: nowrap;","}",".blocklyWidgetDiv .goog-menuitem.goog-menuitem-rtl {","padding-left: 7em;","padding-right: 28px;","}",".blocklyWidgetDiv .goog-menu-nocheckbox .goog-menuitem,",".blocklyWidgetDiv .goog-menu-noicon .goog-menuitem {",
"padding-left: 12px;","}",".blocklyWidgetDiv .goog-menu-noaccel .goog-menuitem {","padding-right: 20px;","}",".blocklyWidgetDiv .goog-menuitem-content {","color: #000;","font: normal 13px Arial, sans-serif;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-accel,",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-content {","color: #ccc !important;","}",".blocklyWidgetDiv .goog-menuitem-disabled .goog-menuitem-icon {","opacity: 0.3;","-moz-opacity: 0.3;","filter: alpha(opacity=30);",
"}",".blocklyWidgetDiv .goog-menuitem-highlight,",".blocklyWidgetDiv .goog-menuitem-hover {","background-color: #d6e9f8;","border-color: #d6e9f8;","border-style: dotted;","border-width: 1px 0;","padding-bottom: 3px;","padding-top: 3px;","}",".blocklyWidgetDiv .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-menuitem-icon {","background-repeat: no-repeat;","height: 16px;","left: 6px;","position: absolute;","right: auto;","vertical-align: middle;","width: 16px;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-checkbox,",
".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-icon {","left: auto;","right: 6px;","}",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-checkbox,",".blocklyWidgetDiv .goog-option-selected .goog-menuitem-icon {","background: url(//ssl.gstatic.com/editor/editortoolbar.png) no-repeat -512px 0;","}",".blocklyWidgetDiv .goog-menuitem-accel {","color: #999;","direction: ltr;","left: auto;","padding: 0 6px;","position: absolute;","right: 0;","text-align: right;","}",".blocklyWidgetDiv .goog-menuitem-rtl .goog-menuitem-accel {",
"left: 0;","right: auto;","text-align: left;","}",".blocklyWidgetDiv .goog-menuitem-mnemonic-hint {","text-decoration: underline;","}",".blocklyWidgetDiv .goog-menuitem-mnemonic-separator {","color: #999;","font-size: 12px;","padding-left: 4px;","}",".blocklyWidgetDiv .goog-menuseparator {","border-top: 1px solid #ccc;","margin: 4px 0;","padding: 0;","}",""];Blockly.WidgetDiv={};Blockly.WidgetDiv.DIV=null;Blockly.WidgetDiv.owner_=null;Blockly.WidgetDiv.dispose_=null;Blockly.WidgetDiv.createDom=function(){Blockly.WidgetDiv.DIV||(Blockly.WidgetDiv.DIV=goog.dom.createDom("div","blocklyWidgetDiv"),document.body.appendChild(Blockly.WidgetDiv.DIV))};
Blockly.WidgetDiv.show=function(a,b,c){Blockly.WidgetDiv.hide();Blockly.WidgetDiv.owner_=a;Blockly.WidgetDiv.dispose_=c;a=goog.style.getViewportPageOffset(document);Blockly.WidgetDiv.DIV.style.top=a.y+"px";Blockly.WidgetDiv.DIV.style.direction=b?"rtl":"ltr";Blockly.WidgetDiv.DIV.style.display="block"};
Blockly.WidgetDiv.hide=function(){Blockly.WidgetDiv.owner_&&(Blockly.WidgetDiv.DIV.style.display="none",Blockly.WidgetDiv.DIV.style.left="",Blockly.WidgetDiv.DIV.style.top="",Blockly.WidgetDiv.DIV.style.height="",Blockly.WidgetDiv.dispose_&&Blockly.WidgetDiv.dispose_(),Blockly.WidgetDiv.owner_=null,Blockly.WidgetDiv.dispose_=null,goog.dom.removeChildren(Blockly.WidgetDiv.DIV))};Blockly.WidgetDiv.isVisible=function(){return!!Blockly.WidgetDiv.owner_};
Blockly.WidgetDiv.hideIfOwner=function(a){Blockly.WidgetDiv.owner_==a&&Blockly.WidgetDiv.hide()};Blockly.WidgetDiv.position=function(a,b,c,d,e){b<d.y&&(b=d.y);e?a>c.width+d.x&&(a=c.width+d.x):a<d.x&&(a=d.x);Blockly.WidgetDiv.DIV.style.left=a+"px";Blockly.WidgetDiv.DIV.style.top=b+"px";Blockly.WidgetDiv.DIV.style.height=c.height-b+d.y+"px"};Blockly.inject=function(a,b){goog.isString(a)&&(a=document.getElementById(a));if(!goog.dom.contains(document,a))throw"Error: container is not in current document.";var c=Blockly.parseOptions_(b||{}),d=Blockly.createDom_(a,c),c=Blockly.createMainWorkspace_(d,c);Blockly.init_(c);c.markFocused();Blockly.bindEvent_(d,"focus",c,c.markFocused);return c};
Blockly.parseToolboxTree_=function(a){a?("string"!=typeof a&&"undefined"==typeof XSLTProcessor&&(a=a.outerHTML),"string"==typeof a&&(a=Blockly.Xml.textToDom(a))):a=null;return a};
Blockly.parseOptions_=function(a){var b=!!a.readOnly;if(b)var c=null,d=!1,e=!1,f=!1,g=!1,h=!1,k=!1;else c=Blockly.parseToolboxTree_(a.toolbox),d=Boolean(c&&c.getElementsByTagName("category").length),e=a.trashcan,void 0===e&&(e=d),f=a.collapse,void 0===f&&(f=d),g=a.comments,void 0===g&&(g=d),h=a.disable,void 0===h&&(h=d),k=a.sounds,void 0===k&&(k=!0);var l=a.scrollbars;void 0===l&&(l=d);var q=a.css;void 0===q&&(q=!0);var m=a.grid||{},p={};p.spacing=parseFloat(m.spacing)||0;p.colour=m.colour||"#888";
p.length=parseFloat(m.length)||1;p.snap=0<p.spacing&&!!m.snap;m="https://blockly-demo.appspot.com/static/media/";a.media?m=a.media:a.path&&(m=a.path+"media/");var n=a.zoom||{},r={};r.controls=void 0===n.controls?!1:!!n.controls;r.wheel=void 0===n.wheel?!1:!!n.wheel;r.startScale=void 0===n.startScale?1:parseFloat(n.startScale);r.maxScale=void 0===n.maxScale?3:parseFloat(n.maxScale);r.minScale=void 0===n.minScale?.3:parseFloat(n.minScale);r.scaleSpeed=void 0===n.scaleSpeed?1.2:parseFloat(n.scaleSpeed);
n=!!a.realtime;return{RTL:!!a.rtl,collapse:f,comments:g,disable:h,readOnly:b,maxBlocks:a.maxBlocks||Infinity,pathToMedia:m,hasCategories:d,hasScrollbars:l,hasTrashcan:e,hasSounds:k,hasCss:q,languageTree:c,gridOptions:p,zoomOptions:r,enableRealtime:n,realtimeOptions:n?a.realtimeOptions:void 0}};
Blockly.parseToolboxTree_=function(a){a?("string"!=typeof a&&("undefined"==typeof XSLTProcessor&&a.outerHTML?a=a.outerHTML:a instanceof Element||(a=null)),"string"==typeof a&&(a=Blockly.Xml.textToDom(a))):a=null;return a};
Blockly.parseOptions_=function(a){var b=!!a.readOnly;if(b)var c=null,d=!1,e=!1,f=!1,g=!1,h=!1,k=!1;else c=Blockly.parseToolboxTree_(a.toolbox),d=Boolean(c&&c.getElementsByTagName("category").length),e=a.trashcan,void 0===e&&(e=d),f=a.collapse,void 0===f&&(f=d),g=a.comments,void 0===g&&(g=d),h=a.disable,void 0===h&&(h=d),k=a.sounds,void 0===k&&(k=!0);var l=a.scrollbars;void 0===l&&(l=d);var m=a.css;void 0===m&&(m=!0);var n=a.grid||{},q={};q.spacing=parseFloat(n.spacing)||0;q.colour=n.colour||"#888";
q.length=parseFloat(n.length)||1;q.snap=0<q.spacing&&!!n.snap;n="https://blockly-demo.appspot.com/static/media/";a.media?n=a.media:a.path&&(n=a.path+"media/");var p=a.zoom||{},r={};r.controls=void 0===p.controls?!1:!!p.controls;r.wheel=void 0===p.wheel?!1:!!p.wheel;r.startScale=void 0===p.startScale?1:parseFloat(p.startScale);r.maxScale=void 0===p.maxScale?3:parseFloat(p.maxScale);r.minScale=void 0===p.minScale?.3:parseFloat(p.minScale);r.scaleSpeed=void 0===p.scaleSpeed?1.2:parseFloat(p.scaleSpeed);
p=!!a.realtime;return{RTL:!!a.rtl,collapse:f,comments:g,disable:h,readOnly:b,maxBlocks:a.maxBlocks||Infinity,pathToMedia:n,hasCategories:d,hasScrollbars:l,hasTrashcan:e,hasSounds:k,hasCss:m,languageTree:c,gridOptions:q,zoomOptions:r,enableRealtime:p,realtimeOptions:p?a.realtimeOptions:void 0}};
Blockly.createDom_=function(a,b){a.setAttribute("dir","LTR");goog.ui.Component.setDefaultRightToLeft(b.RTL);Blockly.Css.inject(b.hasCss,b.pathToMedia);var c=Blockly.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1","class":"blocklySvg"},a),d=Blockly.createSvgElement("defs",{},c),e=String(Math.random()).substring(2),f=Blockly.createSvgElement("filter",{id:"blocklyEmbossFilter"+e},d);Blockly.createSvgElement("feGaussianBlur",
{"in":"SourceAlpha",stdDeviation:1,result:"blur"},f);var g=Blockly.createSvgElement("feSpecularLighting",{"in":"blur",surfaceScale:1,specularConstant:.5,specularExponent:10,"lighting-color":"white",result:"specOut"},f);Blockly.createSvgElement("fePointLight",{x:-5E3,y:-1E4,z:2E4},g);Blockly.createSvgElement("feComposite",{"in":"specOut",in2:"SourceAlpha",operator:"in",result:"specOut"},f);Blockly.createSvgElement("feComposite",{"in":"SourceGraphic",in2:"specOut",operator:"arithmetic",k1:0,k2:1,k3:1,
k4:0},f);b.embossFilterId=f.id;f=Blockly.createSvgElement("pattern",{id:"blocklyDisabledPattern"+e,patternUnits:"userSpaceOnUse",width:10,height:10},d);Blockly.createSvgElement("rect",{width:10,height:10,fill:"#aaa"},f);Blockly.createSvgElement("path",{d:"M 0 0 L 10 10 M 10 0 L 0 10",stroke:"#cc0"},f);b.disabledPatternId=f.id;d=Blockly.createSvgElement("pattern",{id:"blocklyGridPattern"+e,patternUnits:"userSpaceOnUse"},d);0<b.gridOptions.length&&0<b.gridOptions.spacing&&(Blockly.createSvgElement("line",
{stroke:b.gridOptions.colour},d),1<b.gridOptions.length&&Blockly.createSvgElement("line",{stroke:b.gridOptions.colour},d));b.gridPattern=d;return c};
Blockly.createMainWorkspace_=function(a,b){b.parentWorkspace=null;b.getMetrics=Blockly.getMainWorkspaceMetrics_;b.setMetrics=Blockly.setMainWorkspaceMetrics_;var c=new Blockly.WorkspaceSvg(b);c.scale=b.zoomOptions.startScale;a.appendChild(c.createDom("blocklyMainBackground"));c.translate(0,0);c.markFocused();b.readOnly||b.hasScrollbars||c.addChangeListener(function(){if(0==Blockly.dragMode_){var a=c.getMetrics(),e=a.viewLeft+a.absoluteLeft,f=a.viewTop+a.absoluteTop;if(a.contentTop<f||a.contentTop+
a.contentHeight>a.viewHeight+f||a.contentLeft<(b.RTL?a.viewLeft:e)||a.contentLeft+a.contentWidth>(b.RTL?a.viewWidth:a.viewWidth+e))for(var g=c.getTopBlocks(!1),h=0,k;k=g[h];h++){var l=k.getRelativeToSurfaceXY(),q=k.getHeightWidth(),m=f+25-q.height-l.y;0<m&&k.moveBy(0,m);m=f+a.viewHeight-25-l.y;0>m&&k.moveBy(0,m);m=25+e-l.x-(b.RTL?0:q.width);0<m&&k.moveBy(m,0);m=e+a.viewWidth-25-l.x+(b.RTL?q.width:0);0>m&&k.moveBy(m,0)}}});Blockly.svgResize(c);Blockly.WidgetDiv.createDom();Blockly.Tooltip.createDom();
a.contentHeight>a.viewHeight+f||a.contentLeft<(b.RTL?a.viewLeft:e)||a.contentLeft+a.contentWidth>(b.RTL?a.viewWidth:a.viewWidth+e))for(var g=c.getTopBlocks(!1),h=0,k;k=g[h];h++){var l=k.getRelativeToSurfaceXY(),m=k.getHeightWidth(),n=f+25-m.height-l.y;0<n&&k.moveBy(0,n);n=f+a.viewHeight-25-l.y;0>n&&k.moveBy(0,n);n=25+e-l.x-(b.RTL?0:m.width);0<n&&k.moveBy(n,0);n=e+a.viewWidth-25-l.x+(b.RTL?m.width:0);0>n&&k.moveBy(n,0)}}});Blockly.svgResize(c);Blockly.WidgetDiv.createDom();Blockly.Tooltip.createDom();
return c};
Blockly.init_=function(a){var b=a.options,c=a.getParentSvg();Blockly.bindEvent_(c,"contextmenu",null,function(a){Blockly.isTargetInput_(a)||a.preventDefault()});Blockly.bindEvent_(window,"resize",null,function(){Blockly.svgResize(a)});Blockly.documentEventsBound_||(Blockly.bindEvent_(document,"keydown",null,Blockly.onKeyDown_),Blockly.bindEvent_(document,"touchend",null,Blockly.longStop_),Blockly.bindEvent_(document,"touchcancel",null,Blockly.longStop_),document.addEventListener("mouseup",Blockly.onMouseUp_,
!1),goog.userAgent.IPAD&&Blockly.bindEvent_(window,"orientationchange",document,function(){Blockly.fireUiEvent(window,"resize")}),Blockly.documentEventsBound_=!0);b.languageTree&&(a.toolbox_?a.toolbox_.init(a):a.flyout_&&(a.flyout_.init(a),a.flyout_.show(b.languageTree.childNodes),a.scrollX=a.flyout_.width_,b.RTL&&(a.scrollX*=-1),c="translate("+a.scrollX+",0)",a.getCanvas().setAttribute("transform",c),a.getBubbleCanvas().setAttribute("transform",c)));b.hasScrollbars&&(a.scrollbar=new Blockly.ScrollbarPair(a),

File diff suppressed because one or more lines are too long

View file

@ -43,26 +43,9 @@ Blockly.Blocks['text'] = {
this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);
this.setColour(Blockly.Blocks.texts.HUE);
this.appendDummyInput()
.appendField(this.newQuote_(true))
.appendField(new Blockly.FieldTextInput(''), 'TEXT')
.appendField(this.newQuote_(false));
.appendField(new Blockly.FieldTextInput(''), 'TEXT');
this.setOutput(true, 'String');
this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP);
},
/**
* Create an image of an open or closed quote.
* @param {boolean} open True if open quote, false if closed.
* @return {!Blockly.FieldImage} The field image of the quote.
* @this Blockly.Block
* @private
*/
newQuote_: function(open) {
if (open == this.RTL) {
var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==';
} else {
var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC';
}
return new Blockly.FieldImage(file, 12, 12, '"');
}
};
@ -174,9 +157,7 @@ Blockly.Blocks['text_join'] = {
}
// Rebuild block.
if (this.itemCount_ == 0) {
this.appendDummyInput('EMPTY')
.appendField(this.newQuote_(true))
.appendField(this.newQuote_(false));
this.appendDummyInput('EMPTY');
} else {
for (var i = 0; i < this.itemCount_; i++) {
var input = this.appendValueInput('ADD' + i);
@ -185,8 +166,7 @@ Blockly.Blocks['text_join'] = {
}
}
}
},
newQuote_: Blockly.Blocks['text'].newQuote_
}
};
Blockly.Blocks['text_create_join_container'] = {
@ -667,9 +647,7 @@ Blockly.Blocks['text_prompt'] = {
});
this.appendDummyInput()
.appendField(dropdown, 'TYPE')
.appendField(this.newQuote_(true))
.appendField(new Blockly.FieldTextInput(''), 'TEXT')
.appendField(this.newQuote_(false));
.appendField(new Blockly.FieldTextInput(''), 'TEXT');
this.setOutput(true, 'String');
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
@ -679,7 +657,6 @@ Blockly.Blocks['text_prompt'] = {
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER;
});
},
newQuote_: Blockly.Blocks['text'].newQuote_,
updateType_: Blockly.Blocks['text_prompt_ext'].updateType_,
mutationToDom: Blockly.Blocks['text_prompt_ext'].mutationToDom,
domToMutation: Blockly.Blocks['text_prompt_ext'].domToMutation

View file

@ -108,13 +108,11 @@ Blockly.Blocks.procedures_callreturn={init:function(){this.appendDummyInput("TOP
renderArgs_:Blockly.Blocks.procedures_callnoreturn.renderArgs_,mutationToDom:Blockly.Blocks.procedures_callnoreturn.mutationToDom,domToMutation:Blockly.Blocks.procedures_callnoreturn.domToMutation,renameVar:Blockly.Blocks.procedures_callnoreturn.renameVar,customContextMenu:Blockly.Blocks.procedures_callnoreturn.customContextMenu};
Blockly.Blocks.procedures_ifreturn={init:function(){this.appendValueInput("CONDITION").setCheck("Boolean").appendField(Blockly.Msg.CONTROLS_IF_MSG_IF);this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);this.setInputsInline(!0);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Blocks.procedures.HUE);this.setTooltip(Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_IFRETURN_HELPURL);this.hasReturnValue_=!0},
mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("value",Number(this.hasReturnValue_));return a},domToMutation:function(a){this.hasReturnValue_=1==a.getAttribute("value");this.hasReturnValue_||(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN))},onchange:function(){var a=!1,b=this;do{if("procedures_defnoreturn"==b.type||"procedures_defreturn"==b.type){a=!0;break}b=b.getSurroundParent()}while(b);a?("procedures_defnoreturn"==
b.type&&this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!=b.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null)):this.setWarningText(Blockly.Msg.PROCEDURES_IFRETURN_WARNING)}};Blockly.Blocks.texts={};Blockly.Blocks.texts.HUE=160;
Blockly.Blocks.text={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(this.newQuote_(!0)).appendField(new Blockly.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1));this.setOutput(!0,"String");this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP)},newQuote_:function(a){return new Blockly.FieldImage(a==this.RTL?"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC",
12,12,'"')}};
b.type&&this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!=b.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null)):this.setWarningText(Blockly.Msg.PROCEDURES_IFRETURN_WARNING)}};Blockly.Blocks.texts={};Blockly.Blocks.texts.HUE=160;Blockly.Blocks.text={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(new Blockly.FieldTextInput(""),"TEXT");this.setOutput(!0,"String");this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP)}};
Blockly.Blocks.text_join={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_JOIN_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.itemCount_=2;this.updateShape_();this.setOutput(!0,"String");this.setMutator(new Blockly.Mutator(["text_create_join_item"]));this.setTooltip(Blockly.Msg.TEXT_JOIN_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("items",this.itemCount_);return a},domToMutation:function(a){this.itemCount_=parseInt(a.getAttribute("items"),10);
this.updateShape_()},decompose:function(a){var b=a.newBlock("text_create_join_container");b.initSvg();for(var c=b.getInput("STACK").connection,d=0;d<this.itemCount_;d++){var e=a.newBlock("text_create_join_item");e.initSvg();c.connect(e.previousConnection);c=e.nextConnection}return b},compose:function(a){var b=a.getInputTargetBlock("STACK");for(a=[];b;)a.push(b.valueConnection_),b=b.nextConnection&&b.nextConnection.targetBlock();this.itemCount_=a.length;this.updateShape_();for(b=0;b<this.itemCount_;b++)a[b]&&
this.getInput("ADD"+b).connection.connect(a[b])},saveConnections:function(a){a=a.getInputTargetBlock("STACK");for(var b=0;a;){var c=this.getInput("ADD"+b);a.valueConnection_=c&&c.connection.targetConnection;b++;a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){if(this.getInput("EMPTY"))this.removeInput("EMPTY");else for(var a=0;this.getInput("ADD"+a);)this.removeInput("ADD"+a),a++;if(0==this.itemCount_)this.appendDummyInput("EMPTY").appendField(this.newQuote_(!0)).appendField(this.newQuote_(!1));
else for(a=0;a<this.itemCount_;a++){var b=this.appendValueInput("ADD"+a);0==a&&b.appendField(Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH)}},newQuote_:Blockly.Blocks.text.newQuote_};Blockly.Blocks.text_create_join_container={init:function(){this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN);this.appendStatementInput("STACK");this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP);this.contextMenu=!1}};
this.getInput("ADD"+b).connection.connect(a[b])},saveConnections:function(a){a=a.getInputTargetBlock("STACK");for(var b=0;a;){var c=this.getInput("ADD"+b);a.valueConnection_=c&&c.connection.targetConnection;b++;a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){if(this.getInput("EMPTY"))this.removeInput("EMPTY");else for(var a=0;this.getInput("ADD"+a);)this.removeInput("ADD"+a),a++;if(0==this.itemCount_)this.appendDummyInput("EMPTY");else for(a=0;a<this.itemCount_;a++){var b=
this.appendValueInput("ADD"+a);0==a&&b.appendField(Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH)}}};Blockly.Blocks.text_create_join_container={init:function(){this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN);this.appendStatementInput("STACK");this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.text_create_join_item={init:function(){this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.text_append={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_APPEND_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendValueInput("TEXT").appendField(Blockly.Msg.TEXT_APPEND_TO).appendField(new Blockly.FieldVariable(Blockly.Msg.TEXT_APPEND_VARIABLE),"VAR").appendField(Blockly.Msg.TEXT_APPEND_APPENDTEXT);this.setPreviousStatement(!0);this.setNextStatement(!0);var a=this;this.setTooltip(function(){return Blockly.Msg.TEXT_APPEND_TOOLTIP.replace("%1",a.getFieldValue("VAR"))})},
getVars:function(){return[this.getFieldValue("VAR")]},renameVar:function(a,b){Blockly.Names.equals(a,this.getFieldValue("VAR"))&&this.setFieldValue(b,"VAR")}};Blockly.Blocks.text_length={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",colour:Blockly.Blocks.texts.HUE,tooltip:Blockly.Msg.TEXT_LENGTH_TOOLTIP,helpUrl:Blockly.Msg.TEXT_LENGTH_HELPURL})}};
@ -133,8 +131,8 @@ Blockly.Blocks.text_trim={init:function(){var a=[[Blockly.Msg.TEXT_TRIM_OPERATOR
Blockly.Blocks.text_print={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.texts.HUE,tooltip:Blockly.Msg.TEXT_PRINT_TOOLTIP,helpUrl:Blockly.Msg.TEXT_PRINT_HELPURL})}};
Blockly.Blocks.text_prompt_ext={init:function(){var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);var b=this,a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendValueInput("TEXT").appendField(a,"TYPE");this.setOutput(!0,"String");this.setTooltip(function(){return"TEXT"==b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},
updateType_:function(a){"NUMBER"==a?this.outputConnection.setCheck("Number"):this.outputConnection.setCheck("String")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("type",this.getFieldValue("TYPE"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("type"))}};
Blockly.Blocks.text_prompt={init:function(){var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]],b=this;this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendDummyInput().appendField(a,"TYPE").appendField(this.newQuote_(!0)).appendField(new Blockly.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1));this.setOutput(!0,"String");b=this;this.setTooltip(function(){return"TEXT"==
b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},newQuote_:Blockly.Blocks.text.newQuote_,updateType_:Blockly.Blocks.text_prompt_ext.updateType_,mutationToDom:Blockly.Blocks.text_prompt_ext.mutationToDom,domToMutation:Blockly.Blocks.text_prompt_ext.domToMutation};Blockly.Blocks.variables={};Blockly.Blocks.variables.HUE=330;
Blockly.Blocks.text_prompt={init:function(){var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]],b=this;this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendDummyInput().appendField(a,"TYPE").appendField(new Blockly.FieldTextInput(""),"TEXT");this.setOutput(!0,"String");b=this;this.setTooltip(function(){return"TEXT"==b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},updateType_:Blockly.Blocks.text_prompt_ext.updateType_,mutationToDom:Blockly.Blocks.text_prompt_ext.mutationToDom,domToMutation:Blockly.Blocks.text_prompt_ext.domToMutation};Blockly.Blocks.variables={};Blockly.Blocks.variables.HUE=330;
Blockly.Blocks.variables_get={init:function(){this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL);this.setColour(Blockly.Blocks.variables.HUE);this.appendDummyInput().appendField(new Blockly.FieldVariable(Blockly.Msg.VARIABLES_DEFAULT_NAME),"VAR");this.setOutput(!0);this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP);this.contextMenuMsg_=Blockly.Msg.VARIABLES_GET_CREATE_SET},getVars:function(){return[this.getFieldValue("VAR")]},renameVar:function(a,b){Blockly.Names.equals(a,this.getFieldValue("VAR"))&&
this.setFieldValue(b,"VAR")},contextMenuType_:"variables_set",customContextMenu:function(a){var b={enabled:!0},c=this.getFieldValue("VAR");b.text=this.contextMenuMsg_.replace("%1",c);c=goog.dom.createDom("field",null,c);c.setAttribute("name","VAR");c=goog.dom.createDom("block",null,c);c.setAttribute("type",this.contextMenuType_);b.callback=Blockly.ContextMenu.callbackFactory(this,c);a.push(b)}};
Blockly.Blocks.variables_set={init:function(){this.jsonInit({message0:Blockly.Msg.VARIABLES_SET,args0:[{type:"field_variable",name:"VAR",variable:Blockly.Msg.VARIABLES_DEFAULT_NAME},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.variables.HUE,tooltip:Blockly.Msg.VARIABLES_SET_TOOLTIP,helpUrl:Blockly.Msg.VARIABLES_SET_HELPURL});this.contextMenuMsg_=Blockly.Msg.VARIABLES_SET_CREATE_GET},getVars:function(){return[this.getFieldValue("VAR")]},renameVar:function(a,

View file

@ -0,0 +1,106 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2016 MIT
* https://github.com/lkjashdflkjahsdf
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Control blocks for Scratch (Horizontal)
* @author ascii@media.mit.edu <Andrew Sliwinski>
*/
'use strict';
goog.provide('Blockly.Blocks.control');
goog.require('Blockly.Blocks');
Blockly.Blocks['control_repeat'] = {
/**
* Block for repeat n times (external number).
* https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#so57n9
* @this Blockly.Block
*/
init: function() {
this.jsonInit({
"id": "control_repeat",
"message0": "%1 %2 %3",
"args0": [
{
"type": "input_statement",
"name": "DO"
},
{
"type": "field_image",
"src": "../media/icons/control_forever.svg",
"width": 40,
"height": 40,
"alt": "*"
},
{
"type": "input_value",
"name": "TIMES",
"check": "Number"
}
],
"inputsInline": true,
"previousStatement": null,
"nextStatement": null,
"colour": '#F2B827',
"tooltip": "",
"helpUrl": "http://www.example.com/"
});
this.setHelpUrl(function () {
return 'halp me plz. k thx bye.';
});
}
};
Blockly.Blocks['control_forever'] = {
/**
* Block for repeat n times (external number).
* https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#5eke39
* @this Blockly.Block
*/
init: function() {
this.jsonInit({
"id": "control_forever",
"message0": "%1 %2",
"args0": [
{
"type": "input_statement",
"name": "NAME"
},
{
"type": "field_image",
"src": "../media/icons/control_forever.svg",
"width": 40,
"height": 40,
"alt": "*"
}
],
"inputsInline": true,
"previousStatement": null,
"colour": '#F2B827',
"tooltip": ""
});
this.setHelpUrl(function () {
return 'halp me plz. k thx bye.';
});
}
};

View file

@ -0,0 +1,59 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2016 MIT
* https://github.com/lkjashdflkjahsdf
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Control blocks for Scratch (Horizontal)
* @author ascii@media.mit.edu <Andrew Sliwinski>
*/
'use strict';
goog.provide('Blockly.Blocks.event');
goog.require('Blockly.Blocks');
Blockly.Blocks['event_whenflagclicked'] = {
/**
* Block for repeat n times (external number).
* @this Blockly.Block
*/
init: function() {
this.jsonInit({
"id": "event_whenflagclicked",
"message0": "%1",
"args0": [
{
"type": "field_image",
"src": "../media/icons/event_whenflagclicked.svg",
"width": 40,
"height": 40,
"alt": "flag"
}
],
"inputsInline": true,
"nextStatement": null,
"colour": '#F2EC27',
"tooltip": "Do stuff!"
});
this.setHelpUrl(function () {
return 'halp me plz. k thx bye.';
});
}
};

View file

@ -0,0 +1,60 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2016 MIT
* https://github.com/lkjashdflkjahsdf
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Control blocks for Scratch (Horizontal)
* @author ascii@media.mit.edu <Andrew Sliwinski>
*/
'use strict';
goog.provide('Blockly.Blocks.motion');
goog.require('Blockly.Blocks');
Blockly.Blocks['motion_moveright'] = {
/**
* Block for move right (external number)
* https://blockly-demo.appspot.com/static/demos/blockfactory/index.html#ed5ch5
* @this Blockly.Block
*/
init: function() {
this.jsonInit({
"id": "motion_moveright",
"message0": "%1",
"args0": [
{
"type": "field_image",
"src": "../media/icons/motion_moveright.svg",
"width": 40,
"height": 40,
"alt": "*"
}
],
"previousStatement": null,
"nextStatement": null,
"colour": '#25AFF4',
"tooltip": ""
});
this.setHelpUrl(function () {
return 'halp me plz. k thx bye.';
});
}
};

View file

@ -174,9 +174,9 @@ class Gen_compressed(threading.Thread):
self.gen_core()
self.gen_blocks()
self.gen_generator("javascript")
self.gen_generator("python")
self.gen_generator("php")
self.gen_generator("dart")
# self.gen_generator("python")
# self.gen_generator("php")
# self.gen_generator("dart")
def gen_core(self):
target_filename = "blockly_compressed.js"

View file

@ -65,7 +65,7 @@ Blockly.Block = function(workspace, prototypeName, opt_id) {
/** @type {!Array.<!Blockly.Input>} */
this.inputList = [];
/** @type {boolean|undefined} */
this.inputsInline = undefined;
this.inputsInline = true;
/** @type {boolean} */
this.rendered = false;
/** @type {boolean} */

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,7 @@
*/
'use strict';
goog.provide('Blockly.BlockSvg');
// goog.provide('Blockly.BlockSvg');
goog.require('Blockly.Block');
goog.require('Blockly.ContextMenu');

File diff suppressed because it is too large Load diff

View file

@ -50,6 +50,24 @@ Blockly.Connection = function(source, type) {
}
};
/**
* Constant for identifying connections that accept a boolean.
* @const
*/
Blockly.Connection.BOOLEAN = 1;
/**
* Constant for identifying connections that accept a string.
* @const
*/
Blockly.Connection.STRING = 2;
/**
* Constant for identifying connections that accept a number OR null.
* @const
*/
Blockly.Connection.NUMBER = 3;
/**
* Connection this connection connects to. Null if not connected.
* @type {Blockly.Connection}
@ -430,17 +448,10 @@ Blockly.Connection.prototype.moveBy = function(dx, dy) {
*/
Blockly.Connection.prototype.highlight = function() {
var steps;
if (this.type == Blockly.INPUT_VALUE || this.type == Blockly.OUTPUT_VALUE) {
var tabWidth = this.sourceBlock_.RTL ? -Blockly.BlockSvg.TAB_WIDTH :
Blockly.BlockSvg.TAB_WIDTH;
steps = 'm 0,0 v 5 c 0,10 ' + -tabWidth + ',-8 ' + -tabWidth + ',7.5 s ' +
tabWidth + ',-2.5 ' + tabWidth + ',7.5 v 5';
if (this.sourceBlock_.RTL) {
steps = 'm 0,0 v 4 ' + Blockly.BlockSvg.NOTCH_PATH_DOWN + ' v 4';
} else {
if (this.sourceBlock_.RTL) {
steps = 'm 20,0 h -5 ' + Blockly.BlockSvg.NOTCH_PATH_RIGHT + ' h -5';
} else {
steps = 'm -20,0 h 5 ' + Blockly.BlockSvg.NOTCH_PATH_LEFT + ' h 5';
}
steps = 'm 0,0 v -4 ' + Blockly.BlockSvg.NOTCH_PATH_UP + ' v -4';
}
var xy = this.sourceBlock_.getRelativeToSurfaceXY();
var x = this.x_ - xy.x;
@ -654,6 +665,22 @@ Blockly.Connection.prototype.setCheck = function(check) {
return this;
};
/**
* Returns a shape enum for this connection.
* @return {number} Enum representing shape.
*/
Blockly.Connection.prototype.getOutputShape = function() {
if (!this.check_) return Blockly.Connection.NUMBER;
if (this.check_.indexOf('Boolean') !== -1) {
return Blockly.Connection.BOOLEAN;
}
if (this.check_.indexOf('String') !== -1) {
return Blockly.Connection.STRING;
}
return Blockly.Connection.NUMBER;
};
/**
* Change a connection's shadow block.
* @param {Element} shadow DOM representation of a block or null.

View file

@ -178,41 +178,26 @@ Blockly.Css.CONTENT = [
'stroke-width: 4px;',
'}',
'.blocklyPathLight {',
'fill: none;',
'stroke-linecap: round;',
'stroke-width: 1;',
'.blocklyPath {',
// 'stroke: #f00;',
'stroke-width: 1.5px;',
'}',
'.blocklySelected>.blocklyPath {',
'stroke: #fc3;',
'stroke-width: 3px;',
// 'stroke: #fc3;',
// 'stroke-width: 3px;',
'}',
'.blocklySelected>.blocklyPathLight {',
'display: none;',
'}',
'.blocklyDragging>.blocklyPath,',
'.blocklyDragging>.blocklyPathLight {',
'.blocklyDragging>.blocklyPath {',
'fill-opacity: .8;',
'stroke-opacity: .8;',
'}',
'.blocklyDragging>.blocklyPathDark {',
'display: none;',
'}',
'.blocklyDisabled>.blocklyPath {',
'fill-opacity: .5;',
'stroke-opacity: .5;',
'}',
'.blocklyDisabled>.blocklyPathLight,',
'.blocklyDisabled>.blocklyPathDark {',
'display: none;',
'}',
'.blocklyText {',
'cursor: default;',
'fill: #fff;',

View file

@ -119,7 +119,6 @@ Blockly.FieldDropdown.prototype.showEditor_ = function() {
}
}
if (value !== null) {
thisField.sourceBlock_.setShadow(false);
thisField.setValue(value);
}
}

View file

@ -46,8 +46,7 @@ Blockly.FieldImage = function(src, width, height, opt_alt) {
// Ensure height and width are numbers. Strings are bad at math.
this.height_ = Number(height);
this.width_ = Number(width);
this.size_ = new goog.math.Size(this.width_,
this.height_ + 2 * Blockly.BlockSvg.INLINE_PADDING_Y);
this.size_ = new goog.math.Size(this.width_, this.height_);
this.text_ = opt_alt || '';
this.setValue(src);
};

View file

@ -195,7 +195,6 @@ Blockly.FieldTextInput.prototype.onHtmlInputChange_ = function(e) {
// Update source block.
var text = htmlInput.value;
if (text !== htmlInput.oldValue_) {
this.sourceBlock_.setShadow(false);
htmlInput.oldValue_ = text;
this.setText(text);
this.validate_();

View file

@ -1,193 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Helper functions for generating Dart for blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart');
goog.require('Blockly.Generator');
/**
* Dart code generator.
* @type {!Blockly.Generator}
*/
Blockly.Dart = new Blockly.Generator('Dart');
/**
* List of illegal variable names.
* This is not intended to be a security feature. Blockly is 100% client-side,
* so bypassing this list is trivial. This is intended to prevent users from
* accidentally clobbering a built-in object or function.
* @private
*/
Blockly.Dart.addReservedWords(
// https://www.dartlang.org/docs/spec/latest/dart-language-specification.pdf
// Section 16.1.1
'assert,break,case,catch,class,const,continue,default,do,else,enum,extends,false,final,finally,for,if,in,is,new,null,rethrow,return,super,switch,this,throw,true,try,var,void,while,with,' +
// https://api.dartlang.org/dart_core.html
'print,identityHashCode,identical,BidirectionalIterator,Comparable,double,Function,int,Invocation,Iterable,Iterator,List,Map,Match,num,Pattern,RegExp,Set,StackTrace,String,StringSink,Type,bool,DateTime,Deprecated,Duration,Expando,Null,Object,RuneIterator,Runes,Stopwatch,StringBuffer,Symbol,Uri,Comparator,AbstractClassInstantiationError,ArgumentError,AssertionError,CastError,ConcurrentModificationError,CyclicInitializationError,Error,Exception,FallThroughError,FormatException,IntegerDivisionByZeroException,NoSuchMethodError,NullThrownError,OutOfMemoryError,RangeError,StackOverflowError,StateError,TypeError,UnimplementedError,UnsupportedError');
/**
* Order of operation ENUMs.
* https://www.dartlang.org/docs/dart-up-and-running/ch02.html#operator_table
*/
Blockly.Dart.ORDER_ATOMIC = 0; // 0 "" ...
Blockly.Dart.ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] .
Blockly.Dart.ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr
Blockly.Dart.ORDER_MULTIPLICATIVE = 3; // * / % ~/
Blockly.Dart.ORDER_ADDITIVE = 4; // + -
Blockly.Dart.ORDER_SHIFT = 5; // << >>
Blockly.Dart.ORDER_BITWISE_AND = 6; // &
Blockly.Dart.ORDER_BITWISE_XOR = 7; // ^
Blockly.Dart.ORDER_BITWISE_OR = 8; // |
Blockly.Dart.ORDER_RELATIONAL = 9; // >= > <= < as is is!
Blockly.Dart.ORDER_EQUALITY = 10; // == !=
Blockly.Dart.ORDER_LOGICAL_AND = 11; // &&
Blockly.Dart.ORDER_LOGICAL_OR = 12; // ||
Blockly.Dart.ORDER_CONDITIONAL = 13; // expr ? expr : expr
Blockly.Dart.ORDER_CASCADE = 14; // ..
Blockly.Dart.ORDER_ASSIGNMENT = 15; // = *= /= ~/= %= += -= <<= >>= &= ^= |=
Blockly.Dart.ORDER_NONE = 99; // (...)
/**
* Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/
Blockly.Dart.init = function(workspace) {
// Create a dictionary of definitions to be printed before the code.
Blockly.Dart.definitions_ = Object.create(null);
// Create a dictionary mapping desired function names in definitions_
// to actual function names (to avoid collisions with user functions).
Blockly.Dart.functionNames_ = Object.create(null);
if (!Blockly.Dart.variableDB_) {
Blockly.Dart.variableDB_ =
new Blockly.Names(Blockly.Dart.RESERVED_WORDS_);
} else {
Blockly.Dart.variableDB_.reset();
}
var defvars = [];
var variables = Blockly.Variables.allVariables(workspace);
for (var i = 0; i < variables.length; i++) {
defvars[i] = 'var ' +
Blockly.Dart.variableDB_.getName(variables[i],
Blockly.Variables.NAME_TYPE) + ';';
}
Blockly.Dart.definitions_['variables'] = defvars.join('\n');
};
/**
* Prepend the generated code with the variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.Dart.finish = function(code) {
// Indent every line.
if (code) {
code = Blockly.Dart.prefixLines(code, Blockly.Dart.INDENT);
}
code = 'main() {\n' + code + '}';
// Convert the definitions dictionary into a list.
var imports = [];
var definitions = [];
for (var name in Blockly.Dart.definitions_) {
var def = Blockly.Dart.definitions_[name];
if (def.match(/^import\s/)) {
imports.push(def);
} else {
definitions.push(def);
}
}
// Clean up temporary data.
delete Blockly.Dart.definitions_;
delete Blockly.Dart.functionNames_;
Blockly.Dart.variableDB_.reset();
var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
};
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything. A trailing semicolon is needed to make this legal.
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.Dart.scrubNakedValue = function(line) {
return line + ';\n';
};
/**
* Encode a string as a properly escaped Dart string, complete with quotes.
* @param {string} string Text to encode.
* @return {string} Dart string.
* @private
*/
Blockly.Dart.quote_ = function(string) {
// TODO: This is a quick hack. Replace with goog.string.quote
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/\$/g, '\\$')
.replace(/'/g, '\\\'');
return '\'' + string + '\'';
};
/**
* Common tasks for generating Dart from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Blockly.Block} block The current block.
* @param {string} code The Dart code created for this block.
* @return {string} Dart code with comments and subsequent blocks added.
* @private
*/
Blockly.Dart.scrub_ = function(block, code) {
var commentCode = '';
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block.
var comment = block.getCommentText();
if (comment) {
commentCode += Blockly.Dart.prefixLines(comment, '// ') + '\n';
}
// Collect comments for all value arguments.
// Don't collect comments for nested statements.
for (var x = 0; x < block.inputList.length; x++) {
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
var childBlock = block.inputList[x].connection.targetBlock();
if (childBlock) {
var comment = Blockly.Dart.allNestedComments(childBlock);
if (comment) {
commentCode += Blockly.Dart.prefixLines(comment, '// ');
}
}
}
}
}
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
var nextCode = Blockly.Dart.blockToCode(nextBlock);
return commentCode + code + nextCode;
};

View file

@ -1,128 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for colour blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.colour');
goog.require('Blockly.Dart');
Blockly.Dart.addReservedWords('Math');
Blockly.Dart['colour_picker'] = function(block) {
// Colour picker.
var code = '\'' + block.getFieldValue('COLOUR') + '\'';
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['colour_random'] = function(block) {
// Generate a random colour.
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'colour_random',
[ 'String ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ + '() {',
' String hex = \'0123456789abcdef\';',
' var rnd = new Math.Random();',
' return \'#${hex[rnd.nextInt(16)]}${hex[rnd.nextInt(16)]}\'',
' \'${hex[rnd.nextInt(16)]}${hex[rnd.nextInt(16)]}\'',
' \'${hex[rnd.nextInt(16)]}${hex[rnd.nextInt(16)]}\';',
'}']);
var code = functionName + '()';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['colour_rgb'] = function(block) {
// Compose a colour from RGB components expressed as percentages.
var red = Blockly.Dart.valueToCode(block, 'RED',
Blockly.Dart.ORDER_NONE) || 0;
var green = Blockly.Dart.valueToCode(block, 'GREEN',
Blockly.Dart.ORDER_NONE) || 0;
var blue = Blockly.Dart.valueToCode(block, 'BLUE',
Blockly.Dart.ORDER_NONE) || 0;
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'colour_rgb',
[ 'String ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(num r, num g, num b) {',
' num rn = (Math.max(Math.min(r, 1), 0) * 255).round();',
' String rs = rn.toInt().toRadixString(16);',
' rs = \'0$rs\';',
' rs = rs.substring(rs.length - 2);',
' num gn = (Math.max(Math.min(g, 1), 0) * 255).round();',
' String gs = gn.toInt().toRadixString(16);',
' gs = \'0$gs\';',
' gs = gs.substring(gs.length - 2);',
' num bn = (Math.max(Math.min(b, 1), 0) * 255).round();',
' String bs = bn.toInt().toRadixString(16);',
' bs = \'0$bs\';',
' bs = bs.substring(bs.length - 2);',
' return \'#$rs$gs$bs\';',
'}']);
var code = functionName + '(' + red + ', ' + green + ', ' + blue + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['colour_blend'] = function(block) {
// Blend two colours together.
var c1 = Blockly.Dart.valueToCode(block, 'COLOUR1',
Blockly.Dart.ORDER_NONE) || '\'#000000\'';
var c2 = Blockly.Dart.valueToCode(block, 'COLOUR2',
Blockly.Dart.ORDER_NONE) || '\'#000000\'';
var ratio = Blockly.Dart.valueToCode(block, 'RATIO',
Blockly.Dart.ORDER_NONE) || 0.5;
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'colour_blend',
[ 'String ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(String c1, String c2, num ratio) {',
' ratio = Math.max(Math.min(ratio, 1), 0);',
' int r1 = int.parse(\'0x${c1.substring(1, 3)}\');',
' int g1 = int.parse(\'0x${c1.substring(3, 5)}\');',
' int b1 = int.parse(\'0x${c1.substring(5, 7)}\');',
' int r2 = int.parse(\'0x${c2.substring(1, 3)}\');',
' int g2 = int.parse(\'0x${c2.substring(3, 5)}\');',
' int b2 = int.parse(\'0x${c2.substring(5, 7)}\');',
' num rn = (r1 * (1 - ratio) + r2 * ratio).round();',
' String rs = rn.toInt().toRadixString(16);',
' num gn = (g1 * (1 - ratio) + g2 * ratio).round();',
' String gs = gn.toInt().toRadixString(16);',
' num bn = (b1 * (1 - ratio) + b2 * ratio).round();',
' String bs = bn.toInt().toRadixString(16);',
' rs = \'0$rs\';',
' rs = rs.substring(rs.length - 2);',
' gs = \'0$gs\';',
' gs = gs.substring(gs.length - 2);',
' bs = \'0$bs\';',
' bs = bs.substring(bs.length - 2);',
' return \'#$rs$gs$bs\';',
'}']);
var code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

View file

@ -1,335 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for list blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.lists');
goog.require('Blockly.Dart');
Blockly.Dart.addReservedWords('Math');
Blockly.Dart['lists_create_empty'] = function(block) {
// Create an empty list.
return ['[]', Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['lists_create_with'] = function(block) {
// Create a list with any number of elements of any type.
var code = new Array(block.itemCount_);
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.Dart.valueToCode(block, 'ADD' + n,
Blockly.Dart.ORDER_NONE) || 'null';
}
code = '[' + code.join(', ') + ']';
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['lists_repeat'] = function(block) {
// Create a list with one element repeated.
var argument0 = Blockly.Dart.valueToCode(block, 'ITEM',
Blockly.Dart.ORDER_NONE) || 'null';
var argument1 = Blockly.Dart.valueToCode(block, 'NUM',
Blockly.Dart.ORDER_NONE) || '0';
var code = 'new List.filled(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['lists_length'] = function(block) {
// String or array length.
var argument0 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
return [argument0 + '.length', Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['lists_isEmpty'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
return [argument0 + '.isEmpty', Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['lists_indexOf'] = function(block) {
// Find an item in the list.
var operator = block.getFieldValue('END') == 'FIRST' ?
'indexOf' : 'lastIndexOf';
var argument0 = Blockly.Dart.valueToCode(block, 'FIND',
Blockly.Dart.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['lists_getIndex'] = function(block) {
// Get element at index.
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
var mode = block.getFieldValue('MODE') || 'GET';
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.Dart.valueToCode(block, 'AT',
Blockly.Dart.ORDER_UNARY_PREFIX) || '1';
var list = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
if (where == 'FIRST') {
if (mode == 'GET') {
var code = list + '.first';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'GET_REMOVE') {
var code = list + '.removeAt(0)';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'REMOVE') {
return list + '.removeAt(0);\n';
}
} else if (where == 'LAST') {
if (mode == 'GET') {
var code = list + '.last';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'GET_REMOVE') {
var code = list + '.removeLast()';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'REMOVE') {
return list + '.removeLast();\n';
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at += ' - 1';
}
if (mode == 'GET') {
var code = list + '[' + at + ']';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'GET_REMOVE') {
var code = list + '.removeAt(' + at + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'REMOVE') {
return list + '.removeAt(' + at + ');\n';
}
} else if (where == 'FROM_END') {
if (mode == 'GET') {
var functionName = Blockly.Dart.provideFunction_(
'lists_get_from_end',
[ 'dynamic ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList, num x) {',
' x = myList.length - x;',
' return myList.removeAt(x);',
'}']);
code = functionName + '(' + list + ', ' + at + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'GET_REMOVE' || mode == 'REMOVE') {
var functionName = Blockly.Dart.provideFunction_(
'lists_remove_from_end',
[ 'dynamic ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList, num x) {',
' x = myList.length - x;',
' return myList.removeAt(x);',
'}']);
code = functionName + '(' + list + ', ' + at + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'REMOVE') {
return code + ';\n';
}
}
} else if (where == 'RANDOM') {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'lists_get_random_item',
[ 'dynamic ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList, bool remove) {',
' int x = new Math.Random().nextInt(myList.length);',
' if (remove) {',
' return myList.removeAt(x);',
' } else {',
' return myList[x];',
' }',
'}']);
code = functionName + '(' + list + ', ' + (mode != 'GET') + ')';
if (mode == 'GET' || mode == 'GET_REMOVE') {
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else if (mode == 'REMOVE') {
return code + ';\n';
}
}
throw 'Unhandled combination (lists_getIndex).';
};
Blockly.Dart['lists_setIndex'] = function(block) {
// Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
var list = Blockly.Dart.valueToCode(block, 'LIST',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
var mode = block.getFieldValue('MODE') || 'GET';
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.Dart.valueToCode(block, 'AT',
Blockly.Dart.ORDER_ADDITIVE) || '1';
var value = Blockly.Dart.valueToCode(block, 'TO',
Blockly.Dart.ORDER_ASSIGNMENT) || 'null';
// Cache non-trivial values to variables to prevent repeated look-ups.
// Closure, which accesses and modifies 'list'.
function cacheList() {
if (list.match(/^\w+$/)) {
return '';
}
var listVar = Blockly.Dart.variableDB_.getDistinctName(
'tmp_list', Blockly.Variables.NAME_TYPE);
var code = 'List ' + listVar + ' = ' + list + ';\n';
list = listVar;
return code;
}
if (where == 'FIRST') {
if (mode == 'SET') {
return list + '[0] = ' + value + ';\n';
} else if (mode == 'INSERT') {
return list + '.insert(0, ' + value + ');\n';
}
} else if (where == 'LAST') {
if (mode == 'SET') {
var code = cacheList();
code += list + '[' + list + '.length - 1] = ' + value + ';\n';
return code;
} else if (mode == 'INSERT') {
return list + '.add(' + value + ');\n';
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at += ' - 1';
}
if (mode == 'SET') {
return list + '[' + at + '] = ' + value + ';\n';
} else if (mode == 'INSERT') {
return list + '.insert(' + at + ', ' + value + ');\n';
}
} else if (where == 'FROM_END') {
var code = cacheList();
if (mode == 'SET') {
code += list + '[' + list + '.length - ' + at + '] = ' + value + ';\n';
return code;
} else if (mode == 'INSERT') {
code += list + '.insert(' + list + '.length - ' + at + ', ' +
value + ');\n';
return code;
}
} else if (where == 'RANDOM') {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var code = cacheList();
var xVar = Blockly.Dart.variableDB_.getDistinctName(
'tmp_x', Blockly.Variables.NAME_TYPE);
code += 'int ' + xVar +
' = new Math.Random().nextInt(' + list + '.length);';
if (mode == 'SET') {
code += list + '[' + xVar + '] = ' + value + ';\n';
return code;
} else if (mode == 'INSERT') {
code += list + '.insert(' + xVar + ', ' + value + ');\n';
return code;
}
}
throw 'Unhandled combination (lists_setIndex).';
};
Blockly.Dart['lists_getSublist'] = function(block) {
// Get sublist.
var list = Blockly.Dart.valueToCode(block, 'LIST',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
var where1 = block.getFieldValue('WHERE1');
var where2 = block.getFieldValue('WHERE2');
var at1 = Blockly.Dart.valueToCode(block, 'AT1',
Blockly.Dart.ORDER_NONE) || '1';
var at2 = Blockly.Dart.valueToCode(block, 'AT2',
Blockly.Dart.ORDER_NONE) || '1';
if ((where1 == 'FIRST' || where1 == 'FROM_START' && Blockly.isNumber(at1)) &&
(where2 == 'LAST' || where2 == 'FROM_START' && Blockly.isNumber(at2))) {
// Simple case that can be done inline.
at1 = where1 == 'FIRST' ? 0 : parseInt(at1, 10) - 1;
if (where2 == 'LAST') {
code = list + '.sublist(' + at1 + ')';
} else {
at2 = parseInt(at2, 10);
code = list + '.sublist(' + at1 + ', ' + at2 + ')';
}
} else {
var functionName = Blockly.Dart.provideFunction_(
'lists_get_sublist',
[ 'List ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(list, where1, at1, where2, at2) {',
' int getAt(where, at) {',
' if (where == \'FROM_START\') {',
' at--;',
' } else if (where == \'FROM_END\') {',
' at = list.length - at;',
' } else if (where == \'FIRST\') {',
' at = 0;',
' } else if (where == \'LAST\') {',
' at = list.length - 1;',
' } else {',
' throw \'Unhandled option (lists_getSublist).\';',
' }',
' return at;',
' }',
' at1 = getAt(where1, at1);',
' at2 = getAt(where2, at2) + 1;',
' return list.sublist(at1, at2);',
'}']);
var code = functionName + '(' + list + ', \'' +
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')';
}
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['lists_split'] = function(block) {
// Block for splitting text into a list, or joining a list into text.
var value_input = Blockly.Dart.valueToCode(block, 'INPUT',
Blockly.Dart.ORDER_UNARY_POSTFIX);
var value_delim = Blockly.Dart.valueToCode(block, 'DELIM',
Blockly.Dart.ORDER_NONE) || '\'\'';
var mode = block.getFieldValue('MODE');
if (mode == 'SPLIT') {
if (!value_input) {
value_input = '\'\'';
}
var functionName = 'split';
} else if (mode == 'JOIN') {
if (!value_input) {
value_input = '[]';
}
var functionName = 'join';
} else {
throw 'Unknown mode: ' + mode;
}
var code = value_input + '.' + functionName + '(' + value_delim + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

View file

@ -1,125 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for logic blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Dart.logic');
goog.require('Blockly.Dart');
Blockly.Dart['controls_if'] = function(block) {
// If/elseif/else condition.
var n = 0;
var argument = Blockly.Dart.valueToCode(block, 'IF' + n,
Blockly.Dart.ORDER_NONE) || 'false';
var branch = Blockly.Dart.statementToCode(block, 'DO' + n);
var code = 'if (' + argument + ') {\n' + branch + '}';
for (n = 1; n <= block.elseifCount_; n++) {
argument = Blockly.Dart.valueToCode(block, 'IF' + n,
Blockly.Dart.ORDER_NONE) || 'false';
branch = Blockly.Dart.statementToCode(block, 'DO' + n);
code += ' else if (' + argument + ') {\n' + branch + '}';
}
if (block.elseCount_) {
branch = Blockly.Dart.statementToCode(block, 'ELSE');
code += ' else {\n' + branch + '}';
}
return code + '\n';
};
Blockly.Dart['logic_compare'] = function(block) {
// Comparison operator.
var OPERATORS = {
'EQ': '==',
'NEQ': '!=',
'LT': '<',
'LTE': '<=',
'GT': '>',
'GTE': '>='
};
var operator = OPERATORS[block.getFieldValue('OP')];
var order = (operator == '==' || operator == '!=') ?
Blockly.Dart.ORDER_EQUALITY : Blockly.Dart.ORDER_RELATIONAL;
var argument0 = Blockly.Dart.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.Dart.valueToCode(block, 'B', order) || '0';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Dart['logic_operation'] = function(block) {
// Operations 'and', 'or'.
var operator = (block.getFieldValue('OP') == 'AND') ? '&&' : '||';
var order = (operator == '&&') ? Blockly.Dart.ORDER_LOGICAL_AND :
Blockly.Dart.ORDER_LOGICAL_OR;
var argument0 = Blockly.Dart.valueToCode(block, 'A', order);
var argument1 = Blockly.Dart.valueToCode(block, 'B', order);
if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false.
argument0 = 'false';
argument1 = 'false';
} else {
// Single missing arguments have no effect on the return value.
var defaultArgument = (operator == '&&') ? 'true' : 'false';
if (!argument0) {
argument0 = defaultArgument;
}
if (!argument1) {
argument1 = defaultArgument;
}
}
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Dart['logic_negate'] = function(block) {
// Negation.
var order = Blockly.Dart.ORDER_UNARY_PREFIX;
var argument0 = Blockly.Dart.valueToCode(block, 'BOOL', order) || 'true';
var code = '!' + argument0;
return [code, order];
};
Blockly.Dart['logic_boolean'] = function(block) {
// Boolean values true and false.
var code = (block.getFieldValue('BOOL') == 'TRUE') ? 'true' : 'false';
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['logic_null'] = function(block) {
// Null data type.
return ['null', Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['logic_ternary'] = function(block) {
// Ternary operator.
var value_if = Blockly.Dart.valueToCode(block, 'IF',
Blockly.Dart.ORDER_CONDITIONAL) || 'false';
var value_then = Blockly.Dart.valueToCode(block, 'THEN',
Blockly.Dart.ORDER_CONDITIONAL) || 'null';
var value_else = Blockly.Dart.valueToCode(block, 'ELSE',
Blockly.Dart.ORDER_CONDITIONAL) || 'null';
var code = value_if + ' ? ' + value_then + ' : ' + value_else;
return [code, Blockly.Dart.ORDER_CONDITIONAL];
};

View file

@ -1,163 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for loop blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.loops');
goog.require('Blockly.Dart');
Blockly.Dart['controls_repeat_ext'] = function(block) {
// Repeat n times.
if (block.getField('TIMES')) {
// Internal number.
var repeats = String(Number(block.getFieldValue('TIMES')));
} else {
// External number.
var repeats = Blockly.Dart.valueToCode(block, 'TIMES',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
}
var branch = Blockly.Dart.statementToCode(block, 'DO');
branch = Blockly.Dart.addLoopTrap(branch, block.id);
var code = '';
var loopVar = Blockly.Dart.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var endVar = repeats;
if (!repeats.match(/^\w+$/) && !Blockly.isNumber(repeats)) {
var endVar = Blockly.Dart.variableDB_.getDistinctName(
'repeat_end', Blockly.Variables.NAME_TYPE);
code += 'var ' + endVar + ' = ' + repeats + ';\n';
}
code += 'for (int ' + loopVar + ' = 0; ' +
loopVar + ' < ' + endVar + '; ' +
loopVar + '++) {\n' +
branch + '}\n';
return code;
};
Blockly.Dart['controls_repeat'] = Blockly.Dart['controls_repeat_ext'];
Blockly.Dart['controls_whileUntil'] = function(block) {
// Do while/until loop.
var until = block.getFieldValue('MODE') == 'UNTIL';
var argument0 = Blockly.Dart.valueToCode(block, 'BOOL',
until ? Blockly.Dart.ORDER_UNARY_PREFIX :
Blockly.Dart.ORDER_NONE) || 'false';
var branch = Blockly.Dart.statementToCode(block, 'DO');
branch = Blockly.Dart.addLoopTrap(branch, block.id);
if (until) {
argument0 = '!' + argument0;
}
return 'while (' + argument0 + ') {\n' + branch + '}\n';
};
Blockly.Dart['controls_for'] = function(block) {
// For loop.
var variable0 = Blockly.Dart.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Dart.valueToCode(block, 'FROM',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
var argument1 = Blockly.Dart.valueToCode(block, 'TO',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
var increment = Blockly.Dart.valueToCode(block, 'BY',
Blockly.Dart.ORDER_ASSIGNMENT) || '1';
var branch = Blockly.Dart.statementToCode(block, 'DO');
branch = Blockly.Dart.addLoopTrap(branch, block.id);
var code;
if (Blockly.isNumber(argument0) && Blockly.isNumber(argument1) &&
Blockly.isNumber(increment)) {
// All arguments are simple numbers.
var up = parseFloat(argument0) <= parseFloat(argument1);
code = 'for (' + variable0 + ' = ' + argument0 + '; ' +
variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
variable0;
var step = Math.abs(parseFloat(increment));
if (step == 1) {
code += up ? '++' : '--';
} else {
code += (up ? ' += ' : ' -= ') + step;
}
code += ') {\n' + branch + '}\n';
} else {
code = '';
// Cache non-trivial values to variables to prevent repeated look-ups.
var startVar = argument0;
if (!argument0.match(/^\w+$/) && !Blockly.isNumber(argument0)) {
var startVar = Blockly.Dart.variableDB_.getDistinctName(
variable0 + '_start', Blockly.Variables.NAME_TYPE);
code += 'var ' + startVar + ' = ' + argument0 + ';\n';
}
var endVar = argument1;
if (!argument1.match(/^\w+$/) && !Blockly.isNumber(argument1)) {
var endVar = Blockly.Dart.variableDB_.getDistinctName(
variable0 + '_end', Blockly.Variables.NAME_TYPE);
code += 'var ' + endVar + ' = ' + argument1 + ';\n';
}
// Determine loop direction at start, in case one of the bounds
// changes during loop execution.
var incVar = Blockly.Dart.variableDB_.getDistinctName(
variable0 + '_inc', Blockly.Variables.NAME_TYPE);
code += 'num ' + incVar + ' = ';
if (Blockly.isNumber(increment)) {
code += Math.abs(increment) + ';\n';
} else {
code += '(' + increment + ').abs();\n';
}
code += 'if (' + startVar + ' > ' + endVar + ') {\n';
code += Blockly.Dart.INDENT + incVar + ' = -' + incVar + ';\n';
code += '}\n';
code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
' ' + incVar + ' >= 0 ? ' +
variable0 + ' <= ' + endVar + ' : ' +
variable0 + ' >= ' + endVar + ';\n' +
' ' + variable0 + ' += ' + incVar + ') {\n' +
branch + '}\n';
}
return code;
};
Blockly.Dart['controls_forEach'] = function(block) {
// For each loop.
var variable0 = Blockly.Dart.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Dart.valueToCode(block, 'LIST',
Blockly.Dart.ORDER_ASSIGNMENT) || '[]';
var branch = Blockly.Dart.statementToCode(block, 'DO');
branch = Blockly.Dart.addLoopTrap(branch, block.id);
var code = 'for (var ' + variable0 + ' in ' + argument0 + ') {\n' +
branch + '}\n';
return code;
};
Blockly.Dart['controls_flow_statements'] = function(block) {
// Flow statements: continue, break.
switch (block.getFieldValue('FLOW')) {
case 'BREAK':
return 'break;\n';
case 'CONTINUE':
return 'continue;\n';
}
throw 'Unknown flow statement.';
};

View file

@ -1,487 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for math blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Dart.math');
goog.require('Blockly.Dart');
Blockly.Dart.addReservedWords('Math');
Blockly.Dart['math_number'] = function(block) {
// Numeric value.
var code = parseFloat(block.getFieldValue('NUM'));
var order;
if (code == Infinity) {
code = 'double.INFINITY';
order = Blockly.Dart.ORDER_UNARY_POSTFIX;
} else if (code == -Infinity) {
code = '-double.INFINITY';
order = Blockly.Dart.ORDER_UNARY_PREFIX;
} else {
// -4.abs() returns -4 in Dart due to strange order of operation choices.
// -4 is actually an operator and a number. Reflect this in the order.
order = code < 0 ?
Blockly.Dart.ORDER_UNARY_PREFIX : Blockly.Dart.ORDER_ATOMIC;
}
return [code, order];
};
Blockly.Dart['math_arithmetic'] = function(block) {
// Basic arithmetic operators, and power.
var OPERATORS = {
'ADD': [' + ', Blockly.Dart.ORDER_ADDITIVE],
'MINUS': [' - ', Blockly.Dart.ORDER_ADDITIVE],
'MULTIPLY': [' * ', Blockly.Dart.ORDER_MULTIPLICATIVE],
'DIVIDE': [' / ', Blockly.Dart.ORDER_MULTIPLICATIVE],
'POWER': [null, Blockly.Dart.ORDER_NONE] // Handle power separately.
};
var tuple = OPERATORS[block.getFieldValue('OP')];
var operator = tuple[0];
var order = tuple[1];
var argument0 = Blockly.Dart.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.Dart.valueToCode(block, 'B', order) || '0';
var code;
// Power in Dart requires a special case since it has no operator.
if (!operator) {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
code = 'Math.pow(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
}
code = argument0 + operator + argument1;
return [code, order];
};
Blockly.Dart['math_single'] = function(block) {
// Math operators with single operand.
var operator = block.getFieldValue('OP');
var code;
var arg;
if (operator == 'NEG') {
// Negation is a special case given its different operator precedence.
arg = Blockly.Dart.valueToCode(block, 'NUM',
Blockly.Dart.ORDER_UNARY_PREFIX) || '0';
if (arg[0] == '-') {
// --3 is not legal in Dart.
arg = ' ' + arg;
}
code = '-' + arg;
return [code, Blockly.Dart.ORDER_UNARY_PREFIX];
}
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
if (operator == 'ABS' || operator.substring(0, 5) == 'ROUND') {
arg = Blockly.Dart.valueToCode(block, 'NUM',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '0';
} else if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
arg = Blockly.Dart.valueToCode(block, 'NUM',
Blockly.Dart.ORDER_MULTIPLICATIVE) || '0';
} else {
arg = Blockly.Dart.valueToCode(block, 'NUM',
Blockly.Dart.ORDER_NONE) || '0';
}
// First, handle cases which generate values that don't need parentheses
// wrapping the code.
switch (operator) {
case 'ABS':
code = arg + '.abs()';
break;
case 'ROOT':
code = 'Math.sqrt(' + arg + ')';
break;
case 'LN':
code = 'Math.log(' + arg + ')';
break;
case 'EXP':
code = 'Math.exp(' + arg + ')';
break;
case 'POW10':
code = 'Math.pow(10,' + arg + ')';
break;
case 'ROUND':
code = arg + '.round()';
break;
case 'ROUNDUP':
code = arg + '.ceil()';
break;
case 'ROUNDDOWN':
code = arg + '.floor()';
break;
case 'SIN':
code = 'Math.sin(' + arg + ' / 180 * Math.PI)';
break;
case 'COS':
code = 'Math.cos(' + arg + ' / 180 * Math.PI)';
break;
case 'TAN':
code = 'Math.tan(' + arg + ' / 180 * Math.PI)';
break;
}
if (code) {
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
}
// Second, handle cases which generate values that may need parentheses
// wrapping the code.
switch (operator) {
case 'LOG10':
code = 'Math.log(' + arg + ') / Math.log(10)';
break;
case 'ASIN':
code = 'Math.asin(' + arg + ') / Math.PI * 180';
break;
case 'ACOS':
code = 'Math.acos(' + arg + ') / Math.PI * 180';
break;
case 'ATAN':
code = 'Math.atan(' + arg + ') / Math.PI * 180';
break;
default:
throw 'Unknown math operator: ' + operator;
}
return [code, Blockly.Dart.ORDER_MULTIPLICATIVE];
};
Blockly.Dart['math_constant'] = function(block) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
var CONSTANTS = {
'PI': ['Math.PI', Blockly.Dart.ORDER_UNARY_POSTFIX],
'E': ['Math.E', Blockly.Dart.ORDER_UNARY_POSTFIX],
'GOLDEN_RATIO':
['(1 + Math.sqrt(5)) / 2', Blockly.Dart.ORDER_MULTIPLICATIVE],
'SQRT2': ['Math.SQRT2', Blockly.Dart.ORDER_UNARY_POSTFIX],
'SQRT1_2': ['Math.SQRT1_2', Blockly.Dart.ORDER_UNARY_POSTFIX],
'INFINITY': ['double.INFINITY', Blockly.Dart.ORDER_ATOMIC]
};
var constant = block.getFieldValue('CONSTANT');
if (constant != 'INFINITY') {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
}
return CONSTANTS[constant];
};
Blockly.Dart['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false.
var number_to_check = Blockly.Dart.valueToCode(block, 'NUMBER_TO_CHECK',
Blockly.Dart.ORDER_MULTIPLICATIVE);
if (!number_to_check) {
return ['false', Blockly.Python.ORDER_ATOMIC];
}
var dropdown_property = block.getFieldValue('PROPERTY');
var code;
if (dropdown_property == 'PRIME') {
// Prime is a special case as it is not a one-liner test.
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'math_isPrime',
[ 'bool ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ + '(n) {',
' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' if (n == 2 || n == 3) {',
' return true;',
' }',
' // False if n is null, negative, is 1, or not whole.',
' // And false if n is divisible by 2 or 3.',
' if (n == null || n <= 1 || n % 1 != 0 || n % 2 == 0 ||' +
' n % 3 == 0) {',
' return false;',
' }',
' // Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {',
' if (n % (x - 1) == 0 || n % (x + 1) == 0) {',
' return false;',
' }',
' }',
' return true;',
'}']);
code = functionName + '(' + number_to_check + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
}
switch (dropdown_property) {
case 'EVEN':
code = number_to_check + ' % 2 == 0';
break;
case 'ODD':
code = number_to_check + ' % 2 == 1';
break;
case 'WHOLE':
code = number_to_check + ' % 1 == 0';
break;
case 'POSITIVE':
code = number_to_check + ' > 0';
break;
case 'NEGATIVE':
code = number_to_check + ' < 0';
break;
case 'DIVISIBLE_BY':
var divisor = Blockly.Dart.valueToCode(block, 'DIVISOR',
Blockly.Dart.ORDER_MULTIPLICATIVE);
if (!divisor) {
return ['false', Blockly.Python.ORDER_ATOMIC];
}
code = number_to_check + ' % ' + divisor + ' == 0';
break;
}
return [code, Blockly.Dart.ORDER_EQUALITY];
};
Blockly.Dart['math_change'] = function(block) {
// Add to a variable in place.
var argument0 = Blockly.Dart.valueToCode(block, 'DELTA',
Blockly.Dart.ORDER_ADDITIVE) || '0';
var varName = Blockly.Dart.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = (' + varName + ' is num ? ' + varName + ' : 0) + ' +
argument0 + ';\n';
};
// Rounding functions have a single operand.
Blockly.Dart['math_round'] = Blockly.Dart['math_single'];
// Trigonometry functions have a single operand.
Blockly.Dart['math_trig'] = Blockly.Dart['math_single'];
Blockly.Dart['math_on_list'] = function(block) {
// Math functions for lists.
var func = block.getFieldValue('OP');
var list = Blockly.Dart.valueToCode(block, 'LIST',
Blockly.Dart.ORDER_NONE) || '[]';
var code;
switch (func) {
case 'SUM':
var functionName = Blockly.Dart.provideFunction_(
'math_sum',
[ 'num ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' num sumVal = 0;',
' myList.forEach((num entry) {sumVal += entry;});',
' return sumVal;',
'}']);
code = functionName + '(' + list + ')';
break;
case 'MIN':
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'math_min',
[ 'num ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' if (myList.isEmpty) return null;',
' num minVal = myList[0];',
' myList.forEach((num entry) ' +
'{minVal = Math.min(minVal, entry);});',
' return minVal;',
'}']);
code = functionName + '(' + list + ')';
break;
case 'MAX':
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'math_max',
[ 'num ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' if (myList.isEmpty) return null;',
' num maxVal = myList[0];',
' myList.forEach((num entry) ' +
'{maxVal = Math.max(maxVal, entry);});',
' return maxVal;',
'}']);
code = functionName + '(' + list + ')';
break;
case 'AVERAGE':
// This operation exclude null and values that are not int or float:
// math_mean([null,null,"aString",1,9]) == 5.0.
var functionName = Blockly.Dart.provideFunction_(
'math_average',
[ 'num ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' // First filter list for numbers only.',
' List localList = new List.from(myList);',
' localList.removeMatching((a) => a is! num);',
' if (localList.isEmpty) return null;',
' num sumVal = 0;',
' localList.forEach((num entry) {sumVal += entry;});',
' return sumVal / localList.length;',
'}']);
code = functionName + '(' + list + ')';
break;
case 'MEDIAN':
var functionName = Blockly.Dart.provideFunction_(
'math_median',
[ 'num ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' // First filter list for numbers only, then sort, ' +
'then return middle value',
' // or the average of two middle values if list has an ' +
'even number of elements.',
' List localList = new List.from(myList);',
' localList.removeMatching((a) => a is! num);',
' if (localList.isEmpty) return null;',
' localList.sort((a, b) => (a - b));',
' int index = localList.length ~/ 2;',
' if (localList.length % 2 == 1) {',
' return localList[index];',
' } else {',
' return (localList[index - 1] + localList[index]) / 2;',
' }',
'}']);
code = functionName + '(' + list + ')';
break;
case 'MODE':
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
var functionName = Blockly.Dart.provideFunction_(
'math_modes',
[ 'List ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List values) {',
' List modes = [];',
' List counts = [];',
' int maxCount = 0;',
' for (int i = 0; i < values.length; i++) {',
' var value = values[i];',
' bool found = false;',
' int thisCount;',
' for (int j = 0; j < counts.length; j++) {',
' if (counts[j][0] == value) {',
' thisCount = ++counts[j][1];',
' found = true;',
' break;',
' }',
' }',
' if (!found) {',
' counts.add([value, 1]);',
' thisCount = 1;',
' }',
' maxCount = Math.max(thisCount, maxCount);',
' }',
' for (int j = 0; j < counts.length; j++) {',
' if (counts[j][1] == maxCount) {',
' modes.add(counts[j][0]);',
' }',
' }',
' return modes;',
'}']);
code = functionName + '(' + list + ')';
break;
case 'STD_DEV':
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'math_standard_deviation',
[ 'num ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' // First filter list for numbers only.',
' List numbers = new List.from(myList);',
' numbers.removeMatching((a) => a is! num);',
' if (numbers.isEmpty) return null;',
' num n = numbers.length;',
' num sum = 0;',
' numbers.forEach((x) => sum += x);',
' num mean = sum / n;',
' num sumSquare = 0;',
' numbers.forEach((x) => sumSquare += ' +
'Math.pow(x - mean, 2));',
' return Math.sqrt(sumSquare / n);',
'}']);
code = functionName + '(' + list + ')';
break;
case 'RANDOM':
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'math_random_item',
[ 'dynamic ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(List myList) {',
' int x = new Math.Random().nextInt(myList.length);',
' return myList[x];',
'}']);
code = functionName + '(' + list + ')';
break;
default:
throw 'Unknown operator: ' + func;
}
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['math_modulo'] = function(block) {
// Remainder computation.
var argument0 = Blockly.Dart.valueToCode(block, 'DIVIDEND',
Blockly.Dart.ORDER_MULTIPLICATIVE) || '0';
var argument1 = Blockly.Dart.valueToCode(block, 'DIVISOR',
Blockly.Dart.ORDER_MULTIPLICATIVE) || '0';
var code = argument0 + ' % ' + argument1;
return [code, Blockly.Dart.ORDER_MULTIPLICATIVE];
};
Blockly.Dart['math_constrain'] = function(block) {
// Constrain a number between two limits.
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var argument0 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_NONE) || '0';
var argument1 = Blockly.Dart.valueToCode(block, 'LOW',
Blockly.Dart.ORDER_NONE) || '0';
var argument2 = Blockly.Dart.valueToCode(block, 'HIGH',
Blockly.Dart.ORDER_NONE) || 'double.INFINITY';
var code = 'Math.min(Math.max(' + argument0 + ', ' + argument1 + '), ' +
argument2 + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['math_random_int'] = function(block) {
// Random integer between [X] and [Y].
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var argument0 = Blockly.Dart.valueToCode(block, 'FROM',
Blockly.Dart.ORDER_NONE) || '0';
var argument1 = Blockly.Dart.valueToCode(block, 'TO',
Blockly.Dart.ORDER_NONE) || '0';
var functionName = Blockly.Dart.provideFunction_(
'math_random_int',
[ 'int ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ + '(num a, num b) {',
' if (a > b) {',
' // Swap a and b to ensure a is smaller.',
' num c = a;',
' a = b;',
' b = c;',
' }',
' return new Math.Random().nextInt(b - a + 1) + a;',
'}']);
var code = functionName + '(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['math_random_float'] = function(block) {
// Random fraction between 0 and 1.
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
return ['new Math.Random().nextDouble()', Blockly.Dart.ORDER_UNARY_POSTFIX];
};

View file

@ -1,108 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for procedure blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.procedures');
goog.require('Blockly.Dart');
Blockly.Dart['procedures_defreturn'] = function(block) {
// Define a procedure with a return value.
var funcName = Blockly.Dart.variableDB_.getName(block.getFieldValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var branch = Blockly.Dart.statementToCode(block, 'STACK');
if (Blockly.Dart.STATEMENT_PREFIX) {
branch = Blockly.Dart.prefixLines(
Blockly.Dart.STATEMENT_PREFIX.replace(/%1/g,
'\'' + block.id + '\''), Blockly.Dart.INDENT) + branch;
}
if (Blockly.Dart.INFINITE_LOOP_TRAP) {
branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + block.id + '\'') + branch;
}
var returnValue = Blockly.Dart.valueToCode(block, 'RETURN',
Blockly.Dart.ORDER_NONE) || '';
if (returnValue) {
returnValue = ' return ' + returnValue + ';\n';
}
var returnType = returnValue ? 'dynamic' : 'void';
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Dart.variableDB_.getName(block.arguments_[x],
Blockly.Variables.NAME_TYPE);
}
var code = returnType + ' ' + funcName + '(' + args.join(', ') + ') {\n' +
branch + returnValue + '}';
code = Blockly.Dart.scrub_(block, code);
Blockly.Dart.definitions_[funcName] = code;
return null;
};
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
Blockly.Dart['procedures_defnoreturn'] = Blockly.Dart['procedures_defreturn'];
Blockly.Dart['procedures_callreturn'] = function(block) {
// Call a procedure with a return value.
var funcName = Blockly.Dart.variableDB_.getName(block.getFieldValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Dart.valueToCode(block, 'ARG' + x,
Blockly.Dart.ORDER_NONE) || 'null';
}
var code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['procedures_callnoreturn'] = function(block) {
// Call a procedure with no return value.
var funcName = Blockly.Dart.variableDB_.getName(block.getFieldValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Dart.valueToCode(block, 'ARG' + x,
Blockly.Dart.ORDER_NONE) || 'null';
}
var code = funcName + '(' + args.join(', ') + ');\n';
return code;
};
Blockly.Dart['procedures_ifreturn'] = function(block) {
// Conditionally return value from a procedure.
var condition = Blockly.Dart.valueToCode(block, 'CONDITION',
Blockly.Dart.ORDER_NONE) || 'false';
var code = 'if (' + condition + ') {\n';
if (block.hasReturnValue_) {
var value = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_NONE) || 'null';
code += ' return ' + value + ';\n';
} else {
code += ' return;\n';
}
code += '}\n';
return code;
};

View file

@ -1,270 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for text blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.texts');
goog.require('Blockly.Dart');
Blockly.Dart.addReservedWords('Html,Math');
Blockly.Dart['text'] = function(block) {
// Text value.
var code = Blockly.Dart.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['text_join'] = function(block) {
// Create a string made up of any number of elements of any type.
var code;
if (block.itemCount_ == 0) {
return ['\'\'', Blockly.Dart.ORDER_ATOMIC];
} else if (block.itemCount_ == 1) {
var argument0 = Blockly.Dart.valueToCode(block, 'ADD0',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
code = argument0 + '.toString()';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
} else {
code = new Array(block.itemCount_);
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.Dart.valueToCode(block, 'ADD' + n,
Blockly.Dart.ORDER_NONE) || '\'\'';
}
code = '[' + code.join(',') + '].join()';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
}
};
Blockly.Dart['text_append'] = function(block) {
// Append to a variable in place.
var varName = Blockly.Dart.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Dart.valueToCode(block, 'TEXT',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
return varName + ' = [' + varName + ', ' + argument0 + '].join();\n';
};
Blockly.Dart['text_length'] = function(block) {
// String or array length.
var argument0 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
return [argument0 + '.length', Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_isEmpty'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
return [argument0 + '.isEmpty', Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_indexOf'] = function(block) {
// Search the text for a substring.
var operator = block.getFieldValue('END') == 'FIRST' ?
'indexOf' : 'lastIndexOf';
var argument0 = Blockly.Dart.valueToCode(block, 'FIND',
Blockly.Dart.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_charAt'] = function(block) {
// Get letter at index.
// Note: Until January 2013 this block did not have the WHERE input.
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.Dart.valueToCode(block, 'AT',
Blockly.Dart.ORDER_NONE) || '1';
var text = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
switch (where) {
case 'FIRST':
var code = text + '[0]';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
case 'FROM_START':
// Blockly uses one-based indicies.
if (at.match(/^-?\d+$/)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at += ' - 1';
}
var code = text + '[' + at + ']';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
case 'LAST':
at = 1;
// Fall through.
case 'FROM_END':
var functionName = Blockly.Dart.provideFunction_(
'text_get_from_end',
[ 'String ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(String text, num x) {',
' return text[text.length - x];',
'}']);
code = functionName + '(' + text + ', ' + at + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
case 'RANDOM':
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.provideFunction_(
'text_random_letter',
[ 'String ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(String text) {',
' int x = new Math.Random().nextInt(text.length);',
' return text[x];',
'}']);
code = functionName + '(' + text + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
}
throw 'Unhandled option (text_charAt).';
};
Blockly.Dart['text_getSubstring'] = function(block) {
// Get substring.
var text = Blockly.Dart.valueToCode(block, 'STRING',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
var where1 = block.getFieldValue('WHERE1');
var where2 = block.getFieldValue('WHERE2');
var at1 = Blockly.Dart.valueToCode(block, 'AT1',
Blockly.Dart.ORDER_NONE) || '1';
var at2 = Blockly.Dart.valueToCode(block, 'AT2',
Blockly.Dart.ORDER_NONE) || '1';
if (where1 == 'FIRST' && where2 == 'LAST') {
var code = text;
} else {
var functionName = Blockly.Dart.provideFunction_(
'text_get_substring',
[ 'function ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(text, where1, at1, where2, at2) {',
' function getAt(where, at) {',
' if (where == \'FROM_START\') {',
' at--;',
' } else if (where == \'FROM_END\') {',
' at = text.length - at;',
' } else if (where == \'FIRST\') {',
' at = 0;',
' } else if (where == \'LAST\') {',
' at = text.length - 1;',
' } else {',
' throw \'Unhandled option (text_getSubstring).\';',
' }',
' return at;',
' }',
' at1 = getAt(where1, at1);',
' at2 = getAt(where2, at2) + 1;',
' return text.substring(at1, at2);',
'}']);
var code = functionName + '(' + text + ', \'' +
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')';
}
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_changeCase'] = function(block) {
// Change capitalization.
var OPERATORS = {
'UPPERCASE': '.toUpperCase()',
'LOWERCASE': '.toLowerCase()',
'TITLECASE': null
};
var operator = OPERATORS[block.getFieldValue('CASE')];
var code;
if (operator) {
// Upper and lower case are functions built into Dart.
var argument0 = Blockly.Dart.valueToCode(block, 'TEXT',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
code = argument0 + operator;
} else {
// Title case is not a native Dart function. Define one.
var functionName = Blockly.Dart.provideFunction_(
'text_toTitleCase',
[ 'String ' + Blockly.Dart.FUNCTION_NAME_PLACEHOLDER_ +
'(String str) {',
' RegExp exp = new RegExp(r\'\\b\');',
' List<String> list = str.split(exp);',
' final title = new StringBuffer();',
' for (String part in list) {',
' if (part.length > 0) {',
' title.write(part[0].toUpperCase());',
' if (part.length > 0) {',
' title.write(part.substring(1).toLowerCase());',
' }',
' }',
' }',
' return title.toString();',
'}']);
var argument0 = Blockly.Dart.valueToCode(block, 'TEXT',
Blockly.Dart.ORDER_NONE) || '\'\'';
code = functionName + '(' + argument0 + ')';
}
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_trim'] = function(block) {
// Trim spaces.
var OPERATORS = {
'LEFT': '.replaceFirst(new RegExp(r\'^\\s+\'), \'\')',
'RIGHT': '.replaceFirst(new RegExp(r\'\\s+$\'), \'\')',
'BOTH': '.trim()'
};
var operator = OPERATORS[block.getFieldValue('MODE')];
var argument0 = Blockly.Dart.valueToCode(block, 'TEXT',
Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
return [argument0 + operator, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_print'] = function(block) {
// Print statement.
var argument0 = Blockly.Dart.valueToCode(block, 'TEXT',
Blockly.Dart.ORDER_NONE) || '\'\'';
return 'print(' + argument0 + ');\n';
};
Blockly.Dart['text_prompt_ext'] = function(block) {
// Prompt function.
Blockly.Dart.definitions_['import_dart_html'] =
'import \'dart:html\' as Html;';
if (block.getField('TEXT')) {
// Internal message.
var msg = Blockly.Dart.quote_(block.getFieldValue('TEXT'));
} else {
// External message.
var msg = Blockly.Dart.valueToCode(block, 'TEXT',
Blockly.Dart.ORDER_NONE) || '\'\'';
}
var code = 'Html.window.prompt(' + msg + ', \'\')';
var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
if (toNumber) {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
code = 'Math.parseDouble(' + code + ')';
}
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart['text_prompt'] = Blockly.Dart['text_prompt_ext'];

View file

@ -1,46 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2014 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for variable blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.variables');
goog.require('Blockly.Dart');
Blockly.Dart['variables_get'] = function(block) {
// Variable getter.
var code = Blockly.Dart.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart['variables_set'] = function(block) {
// Variable setter.
var argument0 = Blockly.Dart.valueToCode(block, 'VALUE',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
var varName = Blockly.Dart.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + ';\n';
};

View file

@ -0,0 +1,49 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating JavaScript for math blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.JavaScript.control');
goog.require('Blockly.JavaScript');
Blockly.JavaScript['control_repeat'] = function(block) {
// Repeat n times.
var repeats = Blockly.JavaScript.valueToCode(block, 'TIMES',
Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
//
var branch = Blockly.JavaScript.statementToCode(block, 'DO');
branch = Blockly.JavaScript.addLoopTrap(branch, block.id);
//
var code = '';
var loopVar = Blockly.JavaScript.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
code += 'for (var ' + loopVar + ' = 0; ' +
loopVar + ' < ' + repeats + '; ' +
loopVar + '++) {\n' +
branch + '}\n';
return code;
};

View file

@ -19,28 +19,16 @@
*/
/**
* @fileoverview Generating Python for variable blocks.
* @fileoverview Generating JavaScript for math blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.variables');
goog.provide('Blockly.JavaScript.motion');
goog.require('Blockly.Python');
goog.require('Blockly.JavaScript');
Blockly.Python['variables_get'] = function(block) {
// Variable getter.
var code = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['variables_set'] = function(block) {
// Variable setter.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '0';
var varName = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + '\n';
Blockly.JavaScript['motion_moveright'] = function(block) {
var code = 'moveRight();\n';
return code;
};

View file

@ -1,191 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Helper functions for generating PHP for blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP');
goog.require('Blockly.Generator');
/**
* PHP code generator.
* @type {!Blockly.Generator}
*/
Blockly.PHP = new Blockly.Generator('PHP');
/**
* List of illegal variable names.
* This is not intended to be a security feature. Blockly is 100% client-side,
* so bypassing this list is trivial. This is intended to prevent users from
* accidentally clobbering a built-in object or function.
* @private
*/
Blockly.PHP.addReservedWords(
// http://php.net/manual/en/reserved.keywords.php
'__halt_compiler,abstract,and,array,as,break,callable,case,catch,class,clone,const,continue,declare,default,die,do,echo,else,elseif,empty,enddeclare,endfor,endforeach,endif,endswitch,endwhile,eval,exit,extends,final,for,foreach,function,global,goto,if,implements,include,include_once,instanceof,insteadof,interface,isset,list,namespace,new,or,print,private,protected,public,require,require_once,return,static,switch,throw,trait,try,unset,use,var,while,xor,' +
// http://php.net/manual/en/reserved.constants.php
'PHP_VERSION,PHP_MAJOR_VERSION,PHP_MINOR_VERSION,PHP_RELEASE_VERSION,PHP_VERSION_ID,PHP_EXTRA_VERSION,PHP_ZTS,PHP_DEBUG,PHP_MAXPATHLEN,PHP_OS,PHP_SAPI,PHP_EOL,PHP_INT_MAX,PHP_INT_SIZE,DEFAULT_INCLUDE_PATH,PEAR_INSTALL_DIR,PEAR_EXTENSION_DIR,PHP_EXTENSION_DIR,PHP_PREFIX,PHP_BINDIR,PHP_BINARY,PHP_MANDIR,PHP_LIBDIR,PHP_DATADIR,PHP_SYSCONFDIR,PHP_LOCALSTATEDIR,PHP_CONFIG_FILE_PATH,PHP_CONFIG_FILE_SCAN_DIR,PHP_SHLIB_SUFFIX,E_ERROR,E_WARNING,E_PARSE,E_NOTICE,E_CORE_ERROR,E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNING,E_USER_ERROR,E_USER_WARNING,E_USER_NOTICE,E_DEPRECATED,E_USER_DEPRECATED,E_ALL,E_STRICT,__COMPILER_HALT_OFFSET__,TRUE,FALSE,NULL,__CLASS__,__DIR__,__FILE__,__FUNCTION__,__LINE__,__METHOD__,__NAMESPACE__,__TRAIT__');
/**
* Order of operation ENUMs.
* http://php.net/manual/en/language.operators.precedence.php
*/
Blockly.PHP.ORDER_ATOMIC = 0; // 0 "" ...
Blockly.PHP.ORDER_CLONE = 1; // clone
Blockly.PHP.ORDER_NEW = 1; // new
Blockly.PHP.ORDER_MEMBER = 2; // ()
Blockly.PHP.ORDER_FUNCTION_CALL = 2; // ()
Blockly.PHP.ORDER_INCREMENT = 3; // ++
Blockly.PHP.ORDER_DECREMENT = 3; // --
Blockly.PHP.ORDER_LOGICAL_NOT = 4; // !
Blockly.PHP.ORDER_BITWISE_NOT = 4; // ~
Blockly.PHP.ORDER_UNARY_PLUS = 4; // +
Blockly.PHP.ORDER_UNARY_NEGATION = 4; // -
Blockly.PHP.ORDER_MULTIPLICATION = 5; // *
Blockly.PHP.ORDER_DIVISION = 5; // /
Blockly.PHP.ORDER_MODULUS = 5; // %
Blockly.PHP.ORDER_ADDITION = 6; // +
Blockly.PHP.ORDER_SUBTRACTION = 6; // -
Blockly.PHP.ORDER_BITWISE_SHIFT = 7; // << >> >>>
Blockly.PHP.ORDER_RELATIONAL = 8; // < <= > >=
Blockly.PHP.ORDER_IN = 8; // in
Blockly.PHP.ORDER_INSTANCEOF = 8; // instanceof
Blockly.PHP.ORDER_EQUALITY = 9; // == != === !==
Blockly.PHP.ORDER_BITWISE_AND = 10; // &
Blockly.PHP.ORDER_BITWISE_XOR = 11; // ^
Blockly.PHP.ORDER_BITWISE_OR = 12; // |
Blockly.PHP.ORDER_CONDITIONAL = 13; // ?:
Blockly.PHP.ORDER_ASSIGNMENT = 14; // = += -= *= /= %= <<= >>= ...
Blockly.PHP.ORDER_LOGICAL_AND = 15; // &&
Blockly.PHP.ORDER_LOGICAL_OR = 16; // ||
Blockly.PHP.ORDER_COMMA = 17; // ,
Blockly.PHP.ORDER_NONE = 99; // (...)
/**
* Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/
Blockly.PHP.init = function(workspace) {
// Create a dictionary of definitions to be printed before the code.
Blockly.PHP.definitions_ = Object.create(null);
// Create a dictionary mapping desired function names in definitions_
// to actual function names (to avoid collisions with user functions).
Blockly.PHP.functionNames_ = Object.create(null);
if (!Blockly.PHP.variableDB_) {
Blockly.PHP.variableDB_ =
new Blockly.Names(Blockly.PHP.RESERVED_WORDS_, '$');
} else {
Blockly.PHP.variableDB_.reset();
}
var defvars = [];
var variables = Blockly.Variables.allVariables(workspace);
for (var i = 0; i < variables.length; i++) {
defvars[i] = Blockly.PHP.variableDB_.getName(variables[i],
Blockly.Variables.NAME_TYPE) + ';';
}
Blockly.PHP.definitions_['variables'] = defvars.join('\n');
};
/**
* Prepend the generated code with the variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.PHP.finish = function(code) {
// Convert the definitions dictionary into a list.
var definitions = [];
for (var name in Blockly.PHP.definitions_) {
definitions.push(Blockly.PHP.definitions_[name]);
}
// Clean up temporary data.
delete Blockly.PHP.definitions_;
delete Blockly.PHP.functionNames_;
Blockly.PHP.variableDB_.reset();
return definitions.join('\n\n') + '\n\n\n' + code;
};
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything. A trailing semicolon is needed to make this legal.
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.PHP.scrubNakedValue = function(line) {
return line + ';\n';
};
/**
* Encode a string as a properly escaped PHP string, complete with
* quotes.
* @param {string} string Text to encode.
* @return {string} PHP string.
* @private
*/
Blockly.PHP.quote_ = function(string) {
// TODO: This is a quick hack. Replace with goog.string.quote
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/'/g, '\\\'');
return '\'' + string + '\'';
};
/**
* Common tasks for generating PHP from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Blockly.Block} block The current block.
* @param {string} code The PHP code created for this block.
* @return {string} PHP code with comments and subsequent blocks added.
* @private
*/
Blockly.PHP.scrub_ = function(block, code) {
var commentCode = '';
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block.
var comment = block.getCommentText();
if (comment) {
commentCode += Blockly.PHP.prefixLines(comment, '// ') + '\n';
}
// Collect comments for all value arguments.
// Don't collect comments for nested statements.
for (var x = 0; x < block.inputList.length; x++) {
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
var childBlock = block.inputList[x].connection.targetBlock();
if (childBlock) {
var comment = Blockly.PHP.allNestedComments(childBlock);
if (comment) {
commentCode += Blockly.PHP.prefixLines(comment, '// ');
}
}
}
}
}
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
var nextCode = Blockly.PHP.blockToCode(nextBlock);
return commentCode + code + nextCode;
};

View file

@ -1,105 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for colour blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.colour');
goog.require('Blockly.PHP');
Blockly.PHP['colour_picker'] = function(block) {
// Colour picker.
var code = '\'' + block.getFieldValue('COLOUR') + '\'';
return [code, Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['colour_random'] = function(block) {
// Generate a random colour.
var functionName = Blockly.PHP.provideFunction_(
'colour_random',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '() {',
' return \'#\' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), ' +
'6, \'0\', STR_PAD_LEFT);',
'}']);
var code = functionName + '()';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['colour_rgb'] = function(block) {
// Compose a colour from RGB components expressed as percentages.
var red = Blockly.PHP.valueToCode(block, 'RED',
Blockly.PHP.ORDER_COMMA) || 0;
var green = Blockly.PHP.valueToCode(block, 'GREEN',
Blockly.PHP.ORDER_COMMA) || 0;
var blue = Blockly.PHP.valueToCode(block, 'BLUE',
Blockly.PHP.ORDER_COMMA) || 0;
var functionName = Blockly.PHP.provideFunction_(
'colour_rgb',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($r, $g, $b) {',
' $r = round(max(min($r, 100), 0) * 2.55);',
' $g = round(max(min($g, 100), 0) * 2.55);',
' $b = round(max(min($b, 100), 0) * 2.55);',
' $hex = "#";',
' $hex .= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);',
' $hex .= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);',
' $hex .= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);',
' return $hex;',
'}']);
var code = functionName + '(' + red + ', ' + green + ', ' + blue + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['colour_blend'] = function(block) {
// Blend two colours together.
var c1 = Blockly.PHP.valueToCode(block, 'COLOUR1',
Blockly.PHP.ORDER_COMMA) || '\'#000000\'';
var c2 = Blockly.PHP.valueToCode(block, 'COLOUR2',
Blockly.PHP.ORDER_COMMA) || '\'#000000\'';
var ratio = Blockly.PHP.valueToCode(block, 'RATIO',
Blockly.PHP.ORDER_COMMA) || 0.5;
var functionName = Blockly.PHP.provideFunction_(
'colour_blend',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($c1, $c2, $ratio) {',
' $ratio = max(min($ratio, 1), 0);',
' $r1 = hexdec(substr($c1, 1, 2));',
' $g1 = hexdec(substr($c1, 3, 2));',
' $b1 = hexdec(substr($c1, 5, 2));',
' $r2 = hexdec(substr($c2, 1, 2));',
' $g2 = hexdec(substr($c2, 3, 2));',
' $b2 = hexdec(substr($c2, 5, 2));',
' $r = round($r1 * (1 - $ratio) + $r2 * $ratio);',
' $g = round($g1 * (1 - $ratio) + $g2 * $ratio);',
' $b = round($b1 * (1 - $ratio) + $b2 * $ratio);',
' $hex = "#";',
' $hex .= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);',
' $hex .= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);',
' $hex .= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);',
' return $hex;',
'}']);
var code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};

View file

@ -1,381 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for list blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.lists');
goog.require('Blockly.PHP');
Blockly.PHP['lists_create_empty'] = function(block) {
// Create an empty list.
return ['array()', Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['lists_create_with'] = function(block) {
// Create a list with any number of elements of any type.
var code = new Array(block.itemCount_);
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.PHP.valueToCode(block, 'ADD' + n,
Blockly.PHP.ORDER_COMMA) || 'null';
}
code = 'array(' + code.join(', ') + ')';
return [code, Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['lists_repeat'] = function(block) {
// Create a list with one element repeated.
var functionName = Blockly.PHP.provideFunction_(
'lists_repeat',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($value, $count) {',
' $array = array();',
' for ($index = 0; $index < $count; $index++) {',
' $array[] = $value;',
' }',
' return $array;',
'}']);
var argument0 = Blockly.PHP.valueToCode(block, 'ITEM',
Blockly.PHP.ORDER_COMMA) || 'null';
var argument1 = Blockly.PHP.valueToCode(block, 'NUM',
Blockly.PHP.ORDER_COMMA) || '0';
var code = functionName + '(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['lists_length'] = function(block) {
// String or array length.
var functionName = Blockly.PHP.provideFunction_(
'length',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {',
' if (is_string($value)) {',
' return strlen($value);',
' } else {',
' return count($value);',
' }',
'}']);
var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
return [functionName + '(' + argument0 + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['lists_isEmpty'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
return ['empty(' + argument0 + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['lists_indexOf'] = function(block) {
// Find an item in the list.
var operator = block.getFieldValue('END') == 'FIRST' ?
'indexOf' : 'lastIndexOf';
var argument0 = Blockly.PHP.valueToCode(block, 'FIND',
Blockly.PHP.ORDER_NONE) || '\'\'';
var argument1 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_MEMBER) || '[]';
var functionName;
if (block.getFieldValue('END') == 'FIRST'){
// indexOf
functionName = Blockly.PHP.provideFunction_(
'indexOf',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($haystack, $needle) {',
' for ($index = 0; $index < count($haystack); $index++) {',
' if ($haystack[$index] == $needle) return $index+1;',
' }',
' return 0;',
'}']);
} else {
// lastIndexOf
functionName = Blockly.PHP.provideFunction_(
'lastIndexOf',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($haystack, $needle) {',
' $last = 0;',
' for ($index = 0; $index < count($haystack); $index++) {',
' if ($haystack[$index] == $needle) $last = $index+1;',
' }',
' return $last;',
'}']);
}
var code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['lists_getIndex'] = function(block) {
// Get element at index.
var mode = block.getFieldValue('MODE') || 'GET';
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.PHP.valueToCode(block, 'AT',
Blockly.PHP.ORDER_UNARY_NEGATION) || '1';
var list = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
if (where == 'FIRST') {
if (mode == 'GET') {
var code = list + '[0]';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'GET_REMOVE') {
var code = 'array_shift(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return 'array_shift(' + list + ');\n';
}
} else if (where == 'LAST') {
if (mode == 'GET') {
var code = 'end(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'GET_REMOVE') {
var code = 'array_pop(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return 'array_pop(' + list + ');\n';
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseFloat(at) - 1;
} else {
// If the index is dynamic, decrement it in code.
at += ' - 1';
}
if (mode == 'GET') {
var code = list + '[' + at + ']';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'GET_REMOVE') {
var code = 'array_splice(' + list + ', ' + at + ', 1)[0]';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return 'array_splice(' + list + ', ' + at + ', 1);\n';
}
} else if (where == 'FROM_END') {
if (mode == 'GET') {
var code = 'array_slice(' + list + ', -' + at + ', 1)[0]';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'GET_REMOVE' || mode == 'REMOVE') {
code = 'array_splice(' + list +
', count(' + list + ') - ' + at + ', 1)[0]';
if (mode == 'GET_REMOVE') {
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + ';\n';
}
}
} else if (where == 'RANDOM') {
if (mode == 'GET'){
var functionName = Blockly.PHP.provideFunction_(
'lists_get_random_item',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($list) {',
' return $list[rand(0,count($list)-1)];',
'}']);
code = functionName + '(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'GET_REMOVE'){
var functionName = Blockly.PHP.provideFunction_(
'lists_get_remove_random_item',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'(&$list) {',
' $x = rand(0,count($list)-1);',
' unset($list[$x]);',
' return array_values($list);',
'}']);
code = functionName + '(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
var functionName = Blockly.PHP.provideFunction_(
'lists_remove_random_item',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'(&$list) {',
' unset($list[rand(0,count($list)-1)]);',
'}']);
return functionName + '(' + list + ');\n';
}
}
throw 'Unhandled combination (lists_getIndex).';
};
Blockly.PHP['lists_setIndex'] = function(block) {
// Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
var list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_MEMBER) || 'array()';
var mode = block.getFieldValue('MODE') || 'GET';
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.PHP.valueToCode(block, 'AT',
Blockly.PHP.ORDER_NONE) || '1';
var value = Blockly.PHP.valueToCode(block, 'TO',
Blockly.PHP.ORDER_ASSIGNMENT) || 'null';
// Cache non-trivial values to variables to prevent repeated look-ups.
// Closure, which accesses and modifies 'list'.
function cacheList() {
if (list.match(/^\w+$/)) {
return '';
}
var listVar = Blockly.PHP.variableDB_.getDistinctName(
'tmp_list', Blockly.Variables.NAME_TYPE);
var code = listVar + ' = &' + list + ';\n';
list = listVar;
return code;
}
if (where == 'FIRST') {
if (mode == 'SET') {
return list + '[0] = ' + value + ';\n';
} else if (mode == 'INSERT') {
return 'array_unshift(' + list + ', ' + value + ');\n';
}
} else if (where == 'LAST') {
if (mode == 'SET') {
var functionName = Blockly.PHP.provideFunction_(
'lists_set_last_item',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'(&$list, $value) {',
' $list[count($list) - 1] = $value;',
'}']);
return functionName + '(' + list + ', ' + value + ');\n';
} else if (mode == 'INSERT') {
return 'array_push(' + list + ', ' + value + ');\n';
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseFloat(at) - 1;
} else {
// If the index is dynamic, decrement it in code.
at += ' - 1';
}
if (mode == 'SET') {
return list + '[' + at + '] = ' + value + ';\n';
} else if (mode == 'INSERT') {
return 'array_splice(' + list + ', ' + at + ', 0, ' + value + ');\n';
}
} else if (where == 'FROM_END') {
if (mode == 'SET') {
var functionName = Blockly.PHP.provideFunction_(
'lists_set_from_end',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'(&$list, $at, $value) {',
' $list[count($list) - $at] = $value;',
'}']);
return functionName + '(' + list + ', ' + at + ', ' + value + ');\n';
} else if (mode == 'INSERT') {
var functionName = Blockly.PHP.provideFunction_(
'lists_insert_from_end',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'(&$list, $at, $value) {',
' return array_splice($list, count($list) - $at, 0, $value);',
'}']);
return functionName + '(' + list + ', ' + at + ', ' + value + ');\n';
}
} else if (where == 'RANDOM') {
var code = cacheList();
var xVar = Blockly.PHP.variableDB_.getDistinctName(
'tmp_x', Blockly.Variables.NAME_TYPE);
code += xVar + ' = rand(0, count(' + list + ')-1);\n';
if (mode == 'SET') {
code += list + '[' + xVar + '] = ' + value + ';\n';
return code;
} else if (mode == 'INSERT') {
code += 'array_splice(' + list + ', ' + xVar + ', 0, ' + value + ');\n';
return code;
}
}
throw 'Unhandled combination (lists_setIndex).';
};
Blockly.PHP['lists_getSublist'] = function(block) {
// Get sublist.
var list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_MEMBER) || 'array()';
var where1 = block.getFieldValue('WHERE1');
var where2 = block.getFieldValue('WHERE2');
var at1 = Blockly.PHP.valueToCode(block, 'AT1',
Blockly.PHP.ORDER_NONE) || '1';
var at2 = Blockly.PHP.valueToCode(block, 'AT2',
Blockly.PHP.ORDER_NONE) || '1';
if (where1 == 'FIRST' && where2 == 'LAST') {
var code = list;
} else {
var functionName = Blockly.PHP.provideFunction_(
'lists_get_sublist',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($list, $where1, $at1, $where2, $at2) {',
' if ($where2 == \'FROM_START\') {',
' $at2--;',
' } else if ($where2 == \'FROM_END\') {',
' $at2 = $at2 - $at1;',
' } else if ($where2 == \'FIRST\') {',
' $at2 = 0;',
' } else if ($where2 == \'LAST\') {',
' $at2 = count($list);',
' } else {',
' throw \'Unhandled option (lists_getSublist).\';',
' }',
' if ($where1 == \'FROM_START\') {',
' $at1--;',
' } else if ($where1 == \'FROM_END\') {',
' $at1 = count($list) - $at1;',
' } else if ($where1 == \'FIRST\') {',
' $at1 = 0;',
' } else if ($where1 == \'LAST\') {',
' $at1 = count($list) - 1;',
' } else {',
' throw \'Unhandled option (lists_getSublist).\';',
' }',
' return array_slice($list, $at1, $at2);',
'}']);
var code = functionName + '(' + list + ', \'' +
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')';
}
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['lists_split'] = function(block) {
// Block for splitting text into a list, or joining a list into text.
var value_input = Blockly.PHP.valueToCode(block, 'INPUT',
Blockly.PHP.ORDER_MEMBER);
var value_delim = Blockly.PHP.valueToCode(block, 'DELIM',
Blockly.PHP.ORDER_NONE) || '\'\'';
var mode = block.getFieldValue('MODE');
if (mode == 'SPLIT') {
if (!value_input) {
value_input = '\'\'';
}
var functionName = 'explode';
} else if (mode == 'JOIN') {
if (!value_input) {
value_input = 'array()';
}
var functionName = 'implode';
} else {
throw 'Unknown mode: ' + mode;
}
var code = functionName + '(' + value_delim + ', ' + value_input + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};

View file

@ -1,126 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for logic blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.logic');
goog.require('Blockly.PHP');
Blockly.PHP['controls_if'] = function(block) {
// If/elseif/else condition.
var n = 0;
var argument = Blockly.PHP.valueToCode(block, 'IF' + n,
Blockly.PHP.ORDER_NONE) || 'false';
var branch = Blockly.PHP.statementToCode(block, 'DO' + n);
var code = 'if (' + argument + ') {\n' + branch + '}';
for (n = 1; n <= block.elseifCount_; n++) {
argument = Blockly.PHP.valueToCode(block, 'IF' + n,
Blockly.PHP.ORDER_NONE) || 'false';
branch = Blockly.PHP.statementToCode(block, 'DO' + n);
code += ' else if (' + argument + ') {\n' + branch + '}';
}
if (block.elseCount_) {
branch = Blockly.PHP.statementToCode(block, 'ELSE');
code += ' else {\n' + branch + '}';
}
return code + '\n';
};
Blockly.PHP['logic_compare'] = function(block) {
// Comparison operator.
var OPERATORS = {
'EQ': '==',
'NEQ': '!=',
'LT': '<',
'LTE': '<=',
'GT': '>',
'GTE': '>='
};
var operator = OPERATORS[block.getFieldValue('OP')];
var order = (operator == '==' || operator == '!=') ?
Blockly.PHP.ORDER_EQUALITY : Blockly.PHP.ORDER_RELATIONAL;
var argument0 = Blockly.PHP.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.PHP.valueToCode(block, 'B', order) || '0';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.PHP['logic_operation'] = function(block) {
// Operations 'and', 'or'.
var operator = (block.getFieldValue('OP') == 'AND') ? '&&' : '||';
var order = (operator == '&&') ? Blockly.PHP.ORDER_LOGICAL_AND :
Blockly.PHP.ORDER_LOGICAL_OR;
var argument0 = Blockly.PHP.valueToCode(block, 'A', order);
var argument1 = Blockly.PHP.valueToCode(block, 'B', order);
if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false.
argument0 = 'false';
argument1 = 'false';
} else {
// Single missing arguments have no effect on the return value.
var defaultArgument = (operator == '&&') ? 'true' : 'false';
if (!argument0) {
argument0 = defaultArgument;
}
if (!argument1) {
argument1 = defaultArgument;
}
}
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.PHP['logic_negate'] = function(block) {
// Negation.
var order = Blockly.PHP.ORDER_LOGICAL_NOT;
var argument0 = Blockly.PHP.valueToCode(block, 'BOOL', order) ||
'true';
var code = '!' + argument0;
return [code, order];
};
Blockly.PHP['logic_boolean'] = function(block) {
// Boolean values true and false.
var code = (block.getFieldValue('BOOL') == 'TRUE') ? 'true' : 'false';
return [code, Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['logic_null'] = function(block) {
// Null data type.
return ['null', Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['logic_ternary'] = function(block) {
// Ternary operator.
var value_if = Blockly.PHP.valueToCode(block, 'IF',
Blockly.PHP.ORDER_CONDITIONAL) || 'false';
var value_then = Blockly.PHP.valueToCode(block, 'THEN',
Blockly.PHP.ORDER_CONDITIONAL) || 'null';
var value_else = Blockly.PHP.valueToCode(block, 'ELSE',
Blockly.PHP.ORDER_CONDITIONAL) || 'null';
var code = value_if + ' ? ' + value_then + ' : ' + value_else;
return [code, Blockly.PHP.ORDER_CONDITIONAL];
};

View file

@ -1,164 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for loop blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.loops');
goog.require('Blockly.PHP');
Blockly.PHP['controls_repeat_ext'] = function(block) {
// Repeat n times.
if (block.getField('TIMES')) {
// Internal number.
var repeats = String(Number(block.getFieldValue('TIMES')));
} else {
// External number.
var repeats = Blockly.PHP.valueToCode(block, 'TIMES',
Blockly.PHP.ORDER_ASSIGNMENT) || '0';
}
var branch = Blockly.PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block.id);
var code = '';
var loopVar = Blockly.PHP.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var endVar = repeats;
if (!repeats.match(/^\w+$/) && !Blockly.isNumber(repeats)) {
var endVar = Blockly.PHP.variableDB_.getDistinctName(
'repeat_end', Blockly.Variables.NAME_TYPE);
code += endVar + ' = ' + repeats + ';\n';
}
code += 'for (' + loopVar + ' = 0; ' +
loopVar + ' < ' + endVar + '; ' +
loopVar + '++) {\n' +
branch + '}\n';
return code;
};
Blockly.PHP['controls_repeat'] = Blockly.PHP['controls_repeat_ext'];
Blockly.PHP['controls_whileUntil'] = function(block) {
// Do while/until loop.
var until = block.getFieldValue('MODE') == 'UNTIL';
var argument0 = Blockly.PHP.valueToCode(block, 'BOOL',
until ? Blockly.PHP.ORDER_LOGICAL_NOT :
Blockly.PHP.ORDER_NONE) || 'false';
var branch = Blockly.PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block.id);
if (until) {
argument0 = '!' + argument0;
}
return 'while (' + argument0 + ') {\n' + branch + '}\n';
};
Blockly.PHP['controls_for'] = function(block) {
// For loop.
var variable0 = Blockly.PHP.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.PHP.valueToCode(block, 'FROM',
Blockly.PHP.ORDER_ASSIGNMENT) || '0';
var argument1 = Blockly.PHP.valueToCode(block, 'TO',
Blockly.PHP.ORDER_ASSIGNMENT) || '0';
var increment = Blockly.PHP.valueToCode(block, 'BY',
Blockly.PHP.ORDER_ASSIGNMENT) || '1';
var branch = Blockly.PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block.id);
var code;
if (Blockly.isNumber(argument0) && Blockly.isNumber(argument1) &&
Blockly.isNumber(increment)) {
// All arguments are simple numbers.
var up = parseFloat(argument0) <= parseFloat(argument1);
code = 'for (' + variable0 + ' = ' + argument0 + '; ' +
variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
variable0;
var step = Math.abs(parseFloat(increment));
if (step == 1) {
code += up ? '++' : '--';
} else {
code += (up ? ' += ' : ' -= ') + step;
}
code += ') {\n' + branch + '}\n';
} else {
code = '';
// Cache non-trivial values to variables to prevent repeated look-ups.
var startVar = argument0;
if (!argument0.match(/^\w+$/) && !Blockly.isNumber(argument0)) {
startVar = Blockly.PHP.variableDB_.getDistinctName(
variable0 + '_start', Blockly.Variables.NAME_TYPE);
code += startVar + ' = ' + argument0 + ';\n';
}
var endVar = argument1;
if (!argument1.match(/^\w+$/) && !Blockly.isNumber(argument1)) {
var endVar = Blockly.PHP.variableDB_.getDistinctName(
variable0 + '_end', Blockly.Variables.NAME_TYPE);
code += endVar + ' = ' + argument1 + ';\n';
}
// Determine loop direction at start, in case one of the bounds
// changes during loop execution.
var incVar = Blockly.PHP.variableDB_.getDistinctName(
variable0 + '_inc', Blockly.Variables.NAME_TYPE);
code += incVar + ' = ';
if (Blockly.isNumber(increment)) {
code += Math.abs(increment) + ';\n';
} else {
code += 'abs(' + increment + ');\n';
}
code += 'if (' + startVar + ' > ' + endVar + ') {\n';
code += Blockly.PHP.INDENT + incVar + ' = -' + incVar + ';\n';
code += '}\n';
code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
' ' + incVar + ' >= 0 ? ' +
variable0 + ' <= ' + endVar + ' : ' +
variable0 + ' >= ' + endVar + ';\n' +
' ' + variable0 + ' += ' + incVar + ') {\n' +
branch + '}\n';
}
return code;
};
Blockly.PHP['controls_forEach'] = function(block) {
// For each loop.
var variable0 = Blockly.PHP.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_ASSIGNMENT) || '[]';
var branch = Blockly.PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block.id);
var code = '';
code += 'foreach (' + argument0 + ' as ' + variable0 +
') {\n' + branch + '}\n';
return code;
};
Blockly.PHP['controls_flow_statements'] = function(block) {
// Flow statements: continue, break.
switch (block.getFieldValue('FLOW')) {
case 'BREAK':
return 'break;\n';
case 'CONTINUE':
return 'continue;\n';
}
throw 'Unknown flow statement.';
};

View file

@ -1,375 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for math blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.math');
goog.require('Blockly.PHP');
Blockly.PHP['math_number'] = function(block) {
// Numeric value.
var code = parseFloat(block.getFieldValue('NUM'));
if (code == Infinity) {
code = 'INF';
} else if (code == -Infinity) {
code = '-INF';
}
return [code, Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['math_arithmetic'] = function(block) {
// Basic arithmetic operators, and power.
var OPERATORS = {
'ADD': [' + ', Blockly.PHP.ORDER_ADDITION],
'MINUS': [' - ', Blockly.PHP.ORDER_SUBTRACTION],
'MULTIPLY': [' * ', Blockly.PHP.ORDER_MULTIPLICATION],
'DIVIDE': [' / ', Blockly.PHP.ORDER_DIVISION],
'POWER': [null, Blockly.PHP.ORDER_COMMA] // Handle power separately.
};
var tuple = OPERATORS[block.getFieldValue('OP')];
var operator = tuple[0];
var order = tuple[1];
var argument0 = Blockly.PHP.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.PHP.valueToCode(block, 'B', order) || '0';
var code;
// Power in PHP requires a special case since it has no operator.
if (!operator) {
code = 'pow(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
}
code = argument0 + operator + argument1;
return [code, order];
};
Blockly.PHP['math_single'] = function(block) {
// Math operators with single operand.
var operator = block.getFieldValue('OP');
var code;
var arg;
if (operator == 'NEG') {
// Negation is a special case given its different operator precedence.
arg = Blockly.PHP.valueToCode(block, 'NUM',
Blockly.PHP.ORDER_UNARY_NEGATION) || '0';
if (arg[0] == '-') {
// --3 is not legal in JS.
arg = ' ' + arg;
}
code = '-' + arg;
return [code, Blockly.PHP.ORDER_UNARY_NEGATION];
}
if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
arg = Blockly.PHP.valueToCode(block, 'NUM',
Blockly.PHP.ORDER_DIVISION) || '0';
} else {
arg = Blockly.PHP.valueToCode(block, 'NUM',
Blockly.PHP.ORDER_NONE) || '0';
}
// First, handle cases which generate values that don't need parentheses
// wrapping the code.
switch (operator) {
case 'ABS':
code = 'abs(' + arg + ')';
break;
case 'ROOT':
code = 'sqrt(' + arg + ')';
break;
case 'LN':
code = 'log(' + arg + ')';
break;
case 'EXP':
code = 'exp(' + arg + ')';
break;
case 'POW10':
code = 'pow(10,' + arg + ')';
break;
case 'ROUND':
code = 'round(' + arg + ')';
break;
case 'ROUNDUP':
code = 'ceil(' + arg + ')';
break;
case 'ROUNDDOWN':
code = 'floor(' + arg + ')';
break;
case 'SIN':
code = 'sin(' + arg + ' / 180 * pi())';
break;
case 'COS':
code = 'cos(' + arg + ' / 180 * pi())';
break;
case 'TAN':
code = 'tan(' + arg + ' / 180 * pi())';
break;
}
if (code) {
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
}
// Second, handle cases which generate values that may need parentheses
// wrapping the code.
switch (operator) {
case 'LOG10':
code = 'log(' + arg + ') / log(10)';
break;
case 'ASIN':
code = 'asin(' + arg + ') / pi() * 180';
break;
case 'ACOS':
code = 'acos(' + arg + ') / pi() * 180';
break;
case 'ATAN':
code = 'atan(' + arg + ') / pi() * 180';
break;
default:
throw 'Unknown math operator: ' + operator;
}
return [code, Blockly.PHP.ORDER_DIVISION];
};
Blockly.PHP['math_constant'] = function(block) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
var CONSTANTS = {
'PI': ['M_PI', Blockly.PHP.ORDER_ATOMIC],
'E': ['M_E', Blockly.PHP.ORDER_ATOMIC],
'GOLDEN_RATIO': ['(1 + sqrt(5)) / 2', Blockly.PHP.ORDER_DIVISION],
'SQRT2': ['M_SQRT2', Blockly.PHP.ORDER_ATOMIC],
'SQRT1_2': ['M_SQRT1_2', Blockly.PHP.ORDER_ATOMIC],
'INFINITY': ['INF', Blockly.PHP.ORDER_ATOMIC]
};
return CONSTANTS[block.getFieldValue('CONSTANT')];
};
Blockly.PHP['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false.
var number_to_check = Blockly.PHP.valueToCode(block, 'NUMBER_TO_CHECK',
Blockly.PHP.ORDER_MODULUS) || '0';
var dropdown_property = block.getFieldValue('PROPERTY');
var code;
if (dropdown_property == 'PRIME') {
// Prime is a special case as it is not a one-liner test.
var functionName = Blockly.PHP.provideFunction_(
'math_isPrime',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($n) {',
' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' if ($n == 2 || $n == 3) {',
' return true;',
' }',
' // False if n is NaN, negative, is 1, or not whole.',
' // And false if n is divisible by 2 or 3.',
' if (!is_numeric($n) || $n <= 1 || $n % 1 != 0 || $n % 2 == 0 ||' +
' $n % 3 == 0) {',
' return false;',
' }',
' // Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' for ($x = 6; $x <= sqrt($n) + 1; $x += 6) {',
' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {',
' return false;',
' }',
' }',
' return true;',
'}']);
code = functionName + '(' + number_to_check + ')';
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
}
switch (dropdown_property) {
case 'EVEN':
code = number_to_check + ' % 2 == 0';
break;
case 'ODD':
code = number_to_check + ' % 2 == 1';
break;
case 'WHOLE':
code = 'is_int(' + number_to_check + ')';
break;
case 'POSITIVE':
code = number_to_check + ' > 0';
break;
case 'NEGATIVE':
code = number_to_check + ' < 0';
break;
case 'DIVISIBLE_BY':
var divisor = Blockly.PHP.valueToCode(block, 'DIVISOR',
Blockly.PHP.ORDER_MODULUS) || '0';
code = number_to_check + ' % ' + divisor + ' == 0';
break;
}
return [code, Blockly.PHP.ORDER_EQUALITY];
};
Blockly.PHP['math_change'] = function(block) {
// Add to a variable in place.
var argument0 = Blockly.PHP.valueToCode(block, 'DELTA',
Blockly.PHP.ORDER_ADDITION) || '0';
var varName = Blockly.PHP.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
return varName + ' += ' + argument0 + ';\n';
};
// Rounding functions have a single operand.
Blockly.PHP['math_round'] = Blockly.PHP['math_single'];
// Trigonometry functions have a single operand.
Blockly.PHP['math_trig'] = Blockly.PHP['math_single'];
Blockly.PHP['math_on_list'] = function(block) {
// Math functions for lists.
var func = block.getFieldValue('OP');
var list, code;
switch (func) {
case 'SUM':
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
code = 'array_sum(' + list + ')';
break;
case 'MIN':
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
code = 'min(' + list + ')';
break;
case 'MAX':
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
code = 'max(' + list + ')';
break;
case 'AVERAGE':
var functionName = Blockly.PHP.provideFunction_(
'math_mean',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($myList) {',
' return array_sum($myList) / count($myList);',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || 'array()';
code = functionName + '(' + list + ')';
break;
case 'MEDIAN':
var functionName = Blockly.PHP.provideFunction_(
'math_median',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($arr) {',
' sort($arr,SORT_NUMERIC);',
' return (count($arr) % 2) ? $arr[floor(count($arr)/2)] : ',
' ($arr[floor(count($arr)/2)] + $arr[floor(count($arr)/2) - 1]) / 2;',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
break;
case 'MODE':
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
var functionName = Blockly.PHP.provideFunction_(
'math_modes',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($values) {',
' $v = array_count_values($values);',
' arsort($v);',
' foreach($v as $k => $v){$total = $k; break;}',
' return array($total);',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
break;
case 'STD_DEV':
var functionName = Blockly.PHP.provideFunction_(
'math_standard_deviation',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($numbers) {',
' $n = count($numbers);',
' if (!$n) return null;',
' $mean = array_sum($numbers) / count($numbers);',
' foreach($numbers as $key => $num) $devs[$key] = pow($num - $mean, 2);',
' return sqrt(array_sum($devs) / (count($devs) - 1));',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
break;
case 'RANDOM':
var functionName = Blockly.PHP.provideFunction_(
'math_random_list',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($list) {',
' $x = rand(0, count($list)-1);',
' return $list[$x];',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
break;
default:
throw 'Unknown operator: ' + func;
}
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['math_modulo'] = function(block) {
// Remainder computation.
var argument0 = Blockly.PHP.valueToCode(block, 'DIVIDEND',
Blockly.PHP.ORDER_MODULUS) || '0';
var argument1 = Blockly.PHP.valueToCode(block, 'DIVISOR',
Blockly.PHP.ORDER_MODULUS) || '0';
var code = argument0 + ' % ' + argument1;
return [code, Blockly.PHP.ORDER_MODULUS];
};
Blockly.PHP['math_constrain'] = function(block) {
// Constrain a number between two limits.
var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_COMMA) || '0';
var argument1 = Blockly.PHP.valueToCode(block, 'LOW',
Blockly.PHP.ORDER_COMMA) || '0';
var argument2 = Blockly.PHP.valueToCode(block, 'HIGH',
Blockly.PHP.ORDER_COMMA) || 'Infinity';
var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
argument2 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['math_random_int'] = function(block) {
// Random integer between [X] and [Y].
var argument0 = Blockly.PHP.valueToCode(block, 'FROM',
Blockly.PHP.ORDER_COMMA) || '0';
var argument1 = Blockly.PHP.valueToCode(block, 'TO',
Blockly.PHP.ORDER_COMMA) || '0';
var functionName = Blockly.PHP.provideFunction_(
'math_random_int',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($a, $b) {',
' if ($a > $b) {',
' return rand($b, $a);',
' }',
' return rand($a, $b);',
'}']);
var code = functionName + '(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['math_random_float'] = function(block) {
// Random fraction between 0 and 1.
return ['(float)rand()/(float)getrandmax()', Blockly.PHP.ORDER_FUNCTION_CALL];
};

View file

@ -1,122 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for procedure blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.procedures');
goog.require('Blockly.PHP');
Blockly.PHP['procedures_defreturn'] = function(block) {
// Define a procedure with a return value.
// First, add a 'global' statement for every variable that is assigned.
var globals = Blockly.Variables.allVariables(block);
for (var i = globals.length - 1; i >= 0; i--) {
var varName = globals[i];
if (block.arguments_.indexOf(varName) == -1) {
globals[i] = Blockly.PHP.variableDB_.getName(varName,
Blockly.Variables.NAME_TYPE);
} else {
// This variable is actually a parameter name. Do not include it in
// the list of globals, thus allowing it be of local scope.
globals.splice(i, 1);
}
}
globals = globals.length ? ' global ' + globals.join(', ') + ';\n' : '';
var funcName = Blockly.PHP.variableDB_.getName(
block.getFieldValue('NAME'), Blockly.Procedures.NAME_TYPE);
var branch = Blockly.PHP.statementToCode(block, 'STACK');
if (Blockly.PHP.STATEMENT_PREFIX) {
branch = Blockly.PHP.prefixLines(
Blockly.PHP.STATEMENT_PREFIX.replace(/%1/g,
'\'' + block.id + '\''), Blockly.PHP.INDENT) + branch;
}
if (Blockly.PHP.INFINITE_LOOP_TRAP) {
branch = Blockly.PHP.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + block.id + '\'') + branch;
}
var returnValue = Blockly.PHP.valueToCode(block, 'RETURN',
Blockly.PHP.ORDER_NONE) || '';
if (returnValue) {
returnValue = ' return ' + returnValue + ';\n';
}
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.PHP.variableDB_.getName(block.arguments_[x],
Blockly.Variables.NAME_TYPE);
}
var code = 'function ' + funcName + '(' + args.join(', ') + ') {\n' +
globals + branch + returnValue + '}';
code = Blockly.PHP.scrub_(block, code);
Blockly.PHP.definitions_[funcName] = code;
return null;
};
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
Blockly.PHP['procedures_defnoreturn'] =
Blockly.PHP['procedures_defreturn'];
Blockly.PHP['procedures_callreturn'] = function(block) {
// Call a procedure with a return value.
var funcName = Blockly.PHP.variableDB_.getName(
block.getFieldValue('NAME'), Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.PHP.valueToCode(block, 'ARG' + x,
Blockly.PHP.ORDER_COMMA) || 'null';
}
var code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['procedures_callnoreturn'] = function(block) {
// Call a procedure with no return value.
var funcName = Blockly.PHP.variableDB_.getName(
block.getFieldValue('NAME'), Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.PHP.valueToCode(block, 'ARG' + x,
Blockly.PHP.ORDER_COMMA) || 'null';
}
var code = funcName + '(' + args.join(', ') + ');\n';
return code;
};
Blockly.PHP['procedures_ifreturn'] = function(block) {
// Conditionally return value from a procedure.
var condition = Blockly.PHP.valueToCode(block, 'CONDITION',
Blockly.PHP.ORDER_NONE) || 'false';
var code = 'if (' + condition + ') {\n';
if (block.hasReturnValue_) {
var value = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_NONE) || 'null';
code += ' return ' + value + ';\n';
} else {
code += ' return;\n';
}
code += '}\n';
return code;
};

View file

@ -1,260 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for text blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.texts');
goog.require('Blockly.PHP');
Blockly.PHP['text'] = function(block) {
// Text value.
var code = Blockly.PHP.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['text_join'] = function(block) {
// Create a string made up of any number of elements of any type.
var code;
if (block.itemCount_ == 0) {
return ['\'\'', Blockly.PHP.ORDER_ATOMIC];
} else if (block.itemCount_ == 1) {
var argument0 = Blockly.PHP.valueToCode(block, 'ADD0',
Blockly.PHP.ORDER_NONE) || '\'\'';
code = argument0;
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
} else if (block.itemCount_ == 2) {
var argument0 = Blockly.PHP.valueToCode(block, 'ADD0',
Blockly.PHP.ORDER_NONE) || '\'\'';
var argument1 = Blockly.PHP.valueToCode(block, 'ADD1',
Blockly.PHP.ORDER_NONE) || '\'\'';
code = argument0 + ' . ' + argument1;
return [code, Blockly.PHP.ORDER_ADDITION];
} else {
code = new Array(block.itemCount_);
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.PHP.valueToCode(block, 'ADD' + n,
Blockly.PHP.ORDER_COMMA) || '\'\'';
}
code = 'implode(\'\', array(' + code.join(',') + '))';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
}
};
Blockly.PHP['text_append'] = function(block) {
// Append to a variable in place.
var varName = Blockly.PHP.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_NONE) || '\'\'';
return varName + ' .= ' + argument0 + ';\n';
};
Blockly.PHP['text_length'] = function(block) {
// String or array length.
var functionName = Blockly.PHP.provideFunction_(
'length',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {',
' if (is_string($value)) {',
' return strlen($value);',
' } else {',
' return count($value);',
' }',
'}']);
var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
return [functionName + '(' + argument0 + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_isEmpty'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
return ['empty(' + argument0 + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_indexOf'] = function(block) {
// Search the text for a substring.
var operator = block.getFieldValue('END') == 'FIRST' ?
'strpos' : 'strrpos';
var argument0 = Blockly.PHP.valueToCode(block, 'FIND',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
var argument1 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
var code = operator + '(' + argument1 + ', ' + argument0 + ') + 1';
var functionName = Blockly.PHP.provideFunction_(
block.getFieldValue('END') == 'FIRST' ?
'text_indexOf' : 'text_lastIndexOf',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($text, $search) {',
' $pos = ' + operator + '($text, $search);',
' return $pos === false ? 0 : $pos + 1;',
'}']);
code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_charAt'] = function(block) {
// Get letter at index.
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.PHP.valueToCode(block, 'AT',
Blockly.PHP.ORDER_FUNCTION_CALL) || '0';
var text = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
switch (where) {
case 'FIRST':
var code = text + '[0]';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
case 'LAST':
var code = 'substr(' + text + ', -1, 1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
case 'FROM_START':
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseFloat(at) - 1;
} else {
// If the index is dynamic, decrement it in code.
at += ' - 1';
}
var code = 'substr(' + text + ', ' + at + ', 1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
case 'FROM_END':
var code = 'substr(' + text + ', -' + at + ', 1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
case 'RANDOM':
var functionName = Blockly.PHP.provideFunction_(
'text_random_letter',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text) {',
' return $text[rand(0, strlen($text) - 1)];',
'}']);
code = functionName + '(' + text + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
}
throw 'Unhandled option (text_charAt).';
};
Blockly.PHP['text_getSubstring'] = function(block) {
// Get substring.
var text = Blockly.PHP.valueToCode(block, 'STRING',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
var where1 = block.getFieldValue('WHERE1');
var where2 = block.getFieldValue('WHERE2');
var at1 = Blockly.PHP.valueToCode(block, 'AT1',
Blockly.PHP.ORDER_FUNCTION_CALL) || '0';
var at2 = Blockly.PHP.valueToCode(block, 'AT2',
Blockly.PHP.ORDER_FUNCTION_CALL) || '0';
if (where1 == 'FIRST' && where2 == 'LAST') {
var code = text;
} else {
var functionName = Blockly.PHP.provideFunction_(
'text_get_substring',
[ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
'($text, $where1, $at1, $where2, $at2) {',
' if ($where2 == \'FROM_START\') {',
' $at2--;',
' } else if ($where2 == \'FROM_END\') {',
' $at2 = $at2 - $at1;',
' } else if ($where2 == \'FIRST\') {',
' $at2 = 0;',
' } else if ($where2 == \'LAST\') {',
' $at2 = strlen($text);',
' } else { $at2 = 0; }',
' if ($where1 == \'FROM_START\') {',
' $at1--;',
' } else if ($where1 == \'FROM_END\') {',
' $at1 = strlen($text) - $at1;',
' } else if ($where1 == \'FIRST\') {',
' $at1 = 0;',
' } else if ($where1 == \'LAST\') {',
' $at1 = strlen($text) - 1;',
' } else { $at1 = 0; }',
' return substr($text, $at1, $at2);',
'}']);
var code = functionName + '(' + text + ', \'' +
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')';
}
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_changeCase'] = function(block) {
// Change capitalization.
var code;
if (block.getFieldValue('CASE') == 'UPPERCASE') {
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
code = 'strtoupper(' + argument0 + ')';
} else if (block.getFieldValue('CASE') == 'LOWERCASE') {
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
code = 'strtolower(' + argument0 + ')';
} else if (block.getFieldValue('CASE') == 'TITLECASE') {
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_FUNCTION_CALL) || '\'\'';
code = 'ucwords(strtolower(' + argument0 + '))';
}
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_trim'] = function(block) {
// Trim spaces.
var OPERATORS = {
'LEFT': 'ltrim',
'RIGHT': 'rtrim',
'BOTH': 'trim'
};
var operator = OPERATORS[block.getFieldValue('MODE')];
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_NONE) || '\'\'';
return [ operator + '(' + argument0 + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_print'] = function(block) {
// Print statement.
var argument0 = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_NONE) || '\'\'';
return 'print(' + argument0 + ');\n';
};
Blockly.PHP['text_prompt_ext'] = function(block) {
// Prompt function.
if (block.getField('TEXT')) {
// Internal message.
var msg = Blockly.PHP.quote_(block.getFieldValue('TEXT'));
} else {
// External message.
var msg = Blockly.PHP.valueToCode(block, 'TEXT',
Blockly.PHP.ORDER_NONE) || '\'\'';
}
var code = 'readline(' + msg + ')';
var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
if (toNumber) {
code = 'floatval(' + code + ')';
}
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
};
Blockly.PHP['text_prompt'] = Blockly.PHP['text_prompt_ext'];

View file

@ -1,46 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2015 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating PHP for variable blocks.
* @author daarond@gmail.com (Daaron Dwyer)
*/
'use strict';
goog.provide('Blockly.PHP.variables');
goog.require('Blockly.PHP');
Blockly.PHP['variables_get'] = function(block) {
// Variable getter.
var code = Blockly.PHP.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return [code, Blockly.PHP.ORDER_ATOMIC];
};
Blockly.PHP['variables_set'] = function(block) {
// Variable setter.
var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_ASSIGNMENT) || '0';
var varName = Blockly.PHP.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + ';\n';
};

View file

@ -1,199 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Helper functions for generating Python for blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Python');
goog.require('Blockly.Generator');
/**
* Python code generator.
* @type {!Blockly.Generator}
*/
Blockly.Python = new Blockly.Generator('Python');
/**
* List of illegal variable names.
* This is not intended to be a security feature. Blockly is 100% client-side,
* so bypassing this list is trivial. This is intended to prevent users from
* accidentally clobbering a built-in object or function.
* @private
*/
Blockly.Python.addReservedWords(
// import keyword
// print ','.join(keyword.kwlist)
// http://docs.python.org/reference/lexical_analysis.html#keywords
'and,as,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,in,is,lambda,not,or,pass,print,raise,return,try,while,with,yield,' +
//http://docs.python.org/library/constants.html
'True,False,None,NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,' +
// http://docs.python.org/library/functions.html
'abs,divmod,input,open,staticmethod,all,enumerate,int,ord,str,any,eval,isinstance,pow,sum,basestring,execfile,issubclass,print,super,bin,file,iter,property,tuple,bool,filter,len,range,type,bytearray,float,list,raw_input,unichr,callable,format,locals,reduce,unicode,chr,frozenset,long,reload,vars,classmethod,getattr,map,repr,xrange,cmp,globals,max,reversed,zip,compile,hasattr,memoryview,round,__import__,complex,hash,min,set,apply,delattr,help,next,setattr,buffer,dict,hex,object,slice,coerce,dir,id,oct,sorted,intern');
/**
* Order of operation ENUMs.
* http://docs.python.org/reference/expressions.html#summary
*/
Blockly.Python.ORDER_ATOMIC = 0; // 0 "" ...
Blockly.Python.ORDER_COLLECTION = 1; // tuples, lists, dictionaries
Blockly.Python.ORDER_STRING_CONVERSION = 1; // `expression...`
Blockly.Python.ORDER_MEMBER = 2; // . []
Blockly.Python.ORDER_FUNCTION_CALL = 2; // ()
Blockly.Python.ORDER_EXPONENTIATION = 3; // **
Blockly.Python.ORDER_UNARY_SIGN = 4; // + -
Blockly.Python.ORDER_BITWISE_NOT = 4; // ~
Blockly.Python.ORDER_MULTIPLICATIVE = 5; // * / // %
Blockly.Python.ORDER_ADDITIVE = 6; // + -
Blockly.Python.ORDER_BITWISE_SHIFT = 7; // << >>
Blockly.Python.ORDER_BITWISE_AND = 8; // &
Blockly.Python.ORDER_BITWISE_XOR = 9; // ^
Blockly.Python.ORDER_BITWISE_OR = 10; // |
Blockly.Python.ORDER_RELATIONAL = 11; // in, not in, is, is not,
// <, <=, >, >=, <>, !=, ==
Blockly.Python.ORDER_LOGICAL_NOT = 12; // not
Blockly.Python.ORDER_LOGICAL_AND = 13; // and
Blockly.Python.ORDER_LOGICAL_OR = 14; // or
Blockly.Python.ORDER_CONDITIONAL = 15; // if else
Blockly.Python.ORDER_LAMBDA = 16; // lambda
Blockly.Python.ORDER_NONE = 99; // (...)
/**
* Empty loops or conditionals are not allowed in Python.
*/
Blockly.Python.PASS = ' pass\n';
/**
* Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/
Blockly.Python.init = function(workspace) {
// Create a dictionary of definitions to be printed before the code.
Blockly.Python.definitions_ = Object.create(null);
// Create a dictionary mapping desired function names in definitions_
// to actual function names (to avoid collisions with user functions).
Blockly.Python.functionNames_ = Object.create(null);
if (!Blockly.Python.variableDB_) {
Blockly.Python.variableDB_ =
new Blockly.Names(Blockly.Python.RESERVED_WORDS_);
} else {
Blockly.Python.variableDB_.reset();
}
var defvars = [];
var variables = Blockly.Variables.allVariables(workspace);
for (var i = 0; i < variables.length; i++) {
defvars[i] = Blockly.Python.variableDB_.getName(variables[i],
Blockly.Variables.NAME_TYPE) + ' = None';
}
Blockly.Python.definitions_['variables'] = defvars.join('\n');
};
/**
* Prepend the generated code with the variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.Python.finish = function(code) {
// Convert the definitions dictionary into a list.
var imports = [];
var definitions = [];
for (var name in Blockly.Python.definitions_) {
var def = Blockly.Python.definitions_[name];
if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
imports.push(def);
} else {
definitions.push(def);
}
}
// Clean up temporary data.
delete Blockly.Python.definitions_;
delete Blockly.Python.functionNames_;
Blockly.Python.variableDB_.reset();
var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
};
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything.
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.Python.scrubNakedValue = function(line) {
return line + '\n';
};
/**
* Encode a string as a properly escaped Python string, complete with quotes.
* @param {string} string Text to encode.
* @return {string} Python string.
* @private
*/
Blockly.Python.quote_ = function(string) {
// TODO: This is a quick hack. Replace with goog.string.quote
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/\%/g, '\\%')
.replace(/'/g, '\\\'');
return '\'' + string + '\'';
};
/**
* Common tasks for generating Python from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Blockly.Block} block The current block.
* @param {string} code The Python code created for this block.
* @return {string} Python code with comments and subsequent blocks added.
* @private
*/
Blockly.Python.scrub_ = function(block, code) {
var commentCode = '';
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block.
var comment = block.getCommentText();
if (comment) {
commentCode += Blockly.Python.prefixLines(comment, '# ') + '\n';
}
// Collect comments for all value arguments.
// Don't collect comments for nested statements.
for (var x = 0; x < block.inputList.length; x++) {
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
var childBlock = block.inputList[x].connection.targetBlock();
if (childBlock) {
var comment = Blockly.Python.allNestedComments(childBlock);
if (comment) {
commentCode += Blockly.Python.prefixLines(comment, '# ');
}
}
}
}
}
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
var nextCode = Blockly.Python.blockToCode(nextBlock);
return commentCode + code + nextCode;
};

View file

@ -1,86 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for colour blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Python.colour');
goog.require('Blockly.Python');
Blockly.Python['colour_picker'] = function(block) {
// Colour picker.
var code = '\'' + block.getFieldValue('COLOUR') + '\'';
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['colour_random'] = function(block) {
// Generate a random colour.
Blockly.Python.definitions_['import_random'] = 'import random';
var code = '\'#%06x\' % random.randint(0, 2**24 - 1)';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['colour_rgb'] = function(block) {
// Compose a colour from RGB components expressed as percentages.
var functionName = Blockly.Python.provideFunction_(
'colour_rgb',
[ 'def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(r, g, b):',
' r = round(min(100, max(0, r)) * 2.55)',
' g = round(min(100, max(0, g)) * 2.55)',
' b = round(min(100, max(0, b)) * 2.55)',
' return \'#%02x%02x%02x\' % (r, g, b)']);
var r = Blockly.Python.valueToCode(block, 'RED',
Blockly.Python.ORDER_NONE) || 0;
var g = Blockly.Python.valueToCode(block, 'GREEN',
Blockly.Python.ORDER_NONE) || 0;
var b = Blockly.Python.valueToCode(block, 'BLUE',
Blockly.Python.ORDER_NONE) || 0;
var code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['colour_blend'] = function(block) {
// Blend two colours together.
var functionName = Blockly.Python.provideFunction_(
'colour_blend',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
'(colour1, colour2, ratio):',
' r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)',
' g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)',
' b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)',
' ratio = min(1, max(0, ratio))',
' r = round(r1 * (1 - ratio) + r2 * ratio)',
' g = round(g1 * (1 - ratio) + g2 * ratio)',
' b = round(b1 * (1 - ratio) + b2 * ratio)',
' return \'#%02x%02x%02x\' % (r, g, b)']);
var colour1 = Blockly.Python.valueToCode(block, 'COLOUR1',
Blockly.Python.ORDER_NONE) || '\'#000000\'';
var colour2 = Blockly.Python.valueToCode(block, 'COLOUR2',
Blockly.Python.ORDER_NONE) || '\'#000000\'';
var ratio = Blockly.Python.valueToCode(block, 'RATIO',
Blockly.Python.ORDER_NONE) || 0;
var code = functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

View file

@ -1,334 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for list blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.lists');
goog.require('Blockly.Python');
Blockly.Python['lists_create_empty'] = function(block) {
// Create an empty list.
return ['[]', Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['lists_create_with'] = function(block) {
// Create a list with any number of elements of any type.
var code = new Array(block.itemCount_);
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.Python.valueToCode(block, 'ADD' + n,
Blockly.Python.ORDER_NONE) || 'None';
}
code = '[' + code.join(', ') + ']';
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['lists_repeat'] = function(block) {
// Create a list with one element repeated.
var argument0 = Blockly.Python.valueToCode(block, 'ITEM',
Blockly.Python.ORDER_NONE) || 'None';
var argument1 = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var code = '[' + argument0 + '] * ' + argument1;
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};
Blockly.Python['lists_length'] = function(block) {
// String or array length.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '[]';
return ['len(' + argument0 + ')', Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['lists_isEmpty'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '[]';
var code = 'not len(' + argument0 + ')';
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.Python['lists_indexOf'] = function(block) {
// Find an item in the list.
var argument0 = Blockly.Python.valueToCode(block, 'FIND',
Blockly.Python.ORDER_NONE) || '[]';
var argument1 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code;
if (block.getFieldValue('END') == 'FIRST') {
var functionName = Blockly.Python.provideFunction_(
'first_index',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList, elem):',
' try: theIndex = myList.index(elem) + 1',
' except: theIndex = 0',
' return theIndex']);
code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else {
var functionName = Blockly.Python.provideFunction_(
'last_index',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList, elem):',
' try: theIndex = len(myList) - myList[::-1].index(elem)',
' except: theIndex = 0',
' return theIndex']);
code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
};
Blockly.Python['lists_getIndex'] = function(block) {
// Get element at index.
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
var mode = block.getFieldValue('MODE') || 'GET';
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.Python.valueToCode(block, 'AT',
Blockly.Python.ORDER_UNARY_SIGN) || '1';
var list = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '[]';
if (where == 'FIRST') {
if (mode == 'GET') {
var code = list + '[0]';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop(0)';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'LAST') {
if (mode == 'GET') {
var code = list + '[-1]';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop()';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at = 'int(' + at + ' - 1)';
}
if (mode == 'GET') {
var code = list + '[' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop(' + at + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'FROM_END') {
if (mode == 'GET') {
var code = list + '[-' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop(-' + at + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'RANDOM') {
Blockly.Python.definitions_['import_random'] = 'import random';
if (mode == 'GET') {
code = 'random.choice(' + list + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else {
var functionName = Blockly.Python.provideFunction_(
'lists_remove_random_item',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
' x = int(random.random() * len(myList))',
' return myList.pop(x)']);
code = functionName + '(' + list + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
}
throw 'Unhandled combination (lists_getIndex).';
};
Blockly.Python['lists_setIndex'] = function(block) {
// Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
var list = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_MEMBER) || '[]';
var mode = block.getFieldValue('MODE') || 'GET';
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.Python.valueToCode(block, 'AT',
Blockly.Python.ORDER_NONE) || '1';
var value = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || 'None';
// Cache non-trivial values to variables to prevent repeated look-ups.
// Closure, which accesses and modifies 'list'.
function cacheList() {
if (list.match(/^\w+$/)) {
return '';
}
var listVar = Blockly.Python.variableDB_.getDistinctName(
'tmp_list', Blockly.Variables.NAME_TYPE);
var code = listVar + ' = ' + list + '\n';
list = listVar;
return code;
}
if (where == 'FIRST') {
if (mode == 'SET') {
return list + '[0] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.insert(0, ' + value + ')\n';
}
} else if (where == 'LAST') {
if (mode == 'SET') {
return list + '[-1] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.append(' + value + ')\n';
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at = 'int(' + at + ' - 1)';
}
if (mode == 'SET') {
return list + '[' + at + '] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.insert(' + at + ', ' + value + ')\n';
}
} else if (where == 'FROM_END') {
if (mode == 'SET') {
return list + '[-' + at + '] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.insert(-' + at + ', ' + value + ')\n';
}
} else if (where == 'RANDOM') {
Blockly.Python.definitions_['import_random'] = 'import random';
var code = cacheList();
var xVar = Blockly.Python.variableDB_.getDistinctName(
'tmp_x', Blockly.Variables.NAME_TYPE);
code += xVar + ' = int(random.random() * len(' + list + '))\n';
if (mode == 'SET') {
code += list + '[' + xVar + '] = ' + value + '\n';
return code;
} else if (mode == 'INSERT') {
code += list + '.insert(' + xVar + ', ' + value + ')\n';
return code;
}
}
throw 'Unhandled combination (lists_setIndex).';
};
Blockly.Python['lists_getSublist'] = function(block) {
// Get sublist.
var list = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_MEMBER) || '[]';
var where1 = block.getFieldValue('WHERE1');
var where2 = block.getFieldValue('WHERE2');
var at1 = Blockly.Python.valueToCode(block, 'AT1',
Blockly.Python.ORDER_ADDITIVE) || '1';
var at2 = Blockly.Python.valueToCode(block, 'AT2',
Blockly.Python.ORDER_ADDITIVE) || '1';
if (where1 == 'FIRST' || (where1 == 'FROM_START' && at1 == '1')) {
at1 = '';
} else if (where1 == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at1)) {
// If the index is a naked number, decrement it right now.
at1 = parseInt(at1, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at1 = 'int(' + at1 + ' - 1)';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at1)) {
at1 = -parseInt(at1, 10);
} else {
at1 = '-int(' + at1 + ')';
}
}
if (where2 == 'LAST' || (where2 == 'FROM_END' && at2 == '1')) {
at2 = '';
} else if (where1 == 'FROM_START') {
if (Blockly.isNumber(at2)) {
at2 = parseInt(at2, 10);
} else {
at2 = 'int(' + at2 + ')';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at2)) {
// If the index is a naked number, increment it right now.
// Add special case for -0.
at2 = 1 - parseInt(at2, 10);
if (at2 == 0) {
at2 = '';
}
} else {
// If the index is dynamic, increment it in code.
Blockly.Python.definitions_['import_sys'] = 'import sys';
at2 = 'int(1 - ' + at2 + ') or sys.maxsize';
}
}
var code = list + '[' + at1 + ' : ' + at2 + ']';
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['lists_split'] = function(block) {
// Block for splitting text into a list, or joining a list into text.
var mode = block.getFieldValue('MODE');
if (mode == 'SPLIT') {
var value_input = Blockly.Python.valueToCode(block, 'INPUT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var value_delim = Blockly.Python.valueToCode(block, 'DELIM',
Blockly.Python.ORDER_NONE);
var code = value_input + '.split(' + value_delim + ')';
} else if (mode == 'JOIN') {
var value_input = Blockly.Python.valueToCode(block, 'INPUT',
Blockly.Python.ORDER_NONE) || '[]';
var value_delim = Blockly.Python.valueToCode(block, 'DELIM',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = value_delim + '.join(' + value_input + ')';
} else {
throw 'Unknown mode: ' + mode;
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

View file

@ -1,127 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for logic blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.logic');
goog.require('Blockly.Python');
Blockly.Python['controls_if'] = function(block) {
// If/elseif/else condition.
var n = 0;
var argument = Blockly.Python.valueToCode(block, 'IF' + n,
Blockly.Python.ORDER_NONE) || 'False';
var branch = Blockly.Python.statementToCode(block, 'DO' + n) ||
Blockly.Python.PASS;
var code = 'if ' + argument + ':\n' + branch;
for (n = 1; n <= block.elseifCount_; n++) {
argument = Blockly.Python.valueToCode(block, 'IF' + n,
Blockly.Python.ORDER_NONE) || 'False';
branch = Blockly.Python.statementToCode(block, 'DO' + n) ||
Blockly.Python.PASS;
code += 'elif ' + argument + ':\n' + branch;
}
if (block.elseCount_) {
branch = Blockly.Python.statementToCode(block, 'ELSE') ||
Blockly.Python.PASS;
code += 'else:\n' + branch;
}
return code;
};
Blockly.Python['logic_compare'] = function(block) {
// Comparison operator.
var OPERATORS = {
'EQ': '==',
'NEQ': '!=',
'LT': '<',
'LTE': '<=',
'GT': '>',
'GTE': '>='
};
var operator = OPERATORS[block.getFieldValue('OP')];
var order = Blockly.Python.ORDER_RELATIONAL;
var argument0 = Blockly.Python.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'B', order) || '0';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Python['logic_operation'] = function(block) {
// Operations 'and', 'or'.
var operator = (block.getFieldValue('OP') == 'AND') ? 'and' : 'or';
var order = (operator == 'and') ? Blockly.Python.ORDER_LOGICAL_AND :
Blockly.Python.ORDER_LOGICAL_OR;
var argument0 = Blockly.Python.valueToCode(block, 'A', order);
var argument1 = Blockly.Python.valueToCode(block, 'B', order);
if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false.
argument0 = 'False';
argument1 = 'False';
} else {
// Single missing arguments have no effect on the return value.
var defaultArgument = (operator == 'and') ? 'True' : 'False';
if (!argument0) {
argument0 = defaultArgument;
}
if (!argument1) {
argument1 = defaultArgument;
}
}
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Python['logic_negate'] = function(block) {
// Negation.
var argument0 = Blockly.Python.valueToCode(block, 'BOOL',
Blockly.Python.ORDER_LOGICAL_NOT) || 'True';
var code = 'not ' + argument0;
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.Python['logic_boolean'] = function(block) {
// Boolean values true and false.
var code = (block.getFieldValue('BOOL') == 'TRUE') ? 'True' : 'False';
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['logic_null'] = function(block) {
// Null data type.
return ['None', Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['logic_ternary'] = function(block) {
// Ternary operator.
var value_if = Blockly.Python.valueToCode(block, 'IF',
Blockly.Python.ORDER_CONDITIONAL) || 'False';
var value_then = Blockly.Python.valueToCode(block, 'THEN',
Blockly.Python.ORDER_CONDITIONAL) || 'None';
var value_else = Blockly.Python.valueToCode(block, 'ELSE',
Blockly.Python.ORDER_CONDITIONAL) || 'None';
var code = value_then + ' if ' + value_if + ' else ' + value_else;
return [code, Blockly.Python.ORDER_CONDITIONAL];
};

View file

@ -1,211 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for loop blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.loops');
goog.require('Blockly.Python');
Blockly.Python['controls_repeat_ext'] = function(block) {
// Repeat n times.
if (block.getField('TIMES')) {
// Internal number.
var repeats = String(parseInt(block.getFieldValue('TIMES'), 10));
} else {
// External number.
var repeats = Blockly.Python.valueToCode(block, 'TIMES',
Blockly.Python.ORDER_NONE) || '0';
}
if (Blockly.isNumber(repeats)) {
repeats = parseInt(repeats, 10);
} else {
repeats = 'int(' + repeats + ')';
}
var branch = Blockly.Python.statementToCode(block, 'DO');
branch = Blockly.Python.addLoopTrap(branch, block.id) ||
Blockly.Python.PASS;
var loopVar = Blockly.Python.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
return code;
};
Blockly.Python['controls_repeat'] = Blockly.Python['controls_repeat_ext'];
Blockly.Python['controls_whileUntil'] = function(block) {
// Do while/until loop.
var until = block.getFieldValue('MODE') == 'UNTIL';
var argument0 = Blockly.Python.valueToCode(block, 'BOOL',
until ? Blockly.Python.ORDER_LOGICAL_NOT :
Blockly.Python.ORDER_NONE) || 'False';
var branch = Blockly.Python.statementToCode(block, 'DO');
branch = Blockly.Python.addLoopTrap(branch, block.id) ||
Blockly.Python.PASS;
if (until) {
argument0 = 'not ' + argument0;
}
return 'while ' + argument0 + ':\n' + branch;
};
Blockly.Python['controls_for'] = function(block) {
// For loop.
var variable0 = Blockly.Python.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Python.valueToCode(block, 'FROM',
Blockly.Python.ORDER_NONE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || '0';
var increment = Blockly.Python.valueToCode(block, 'BY',
Blockly.Python.ORDER_NONE) || '1';
var branch = Blockly.Python.statementToCode(block, 'DO');
branch = Blockly.Python.addLoopTrap(branch, block.id) ||
Blockly.Python.PASS;
var code = '';
var range;
// Helper functions.
var defineUpRange = function() {
return Blockly.Python.provideFunction_(
'upRange',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
'(start, stop, step):',
' while start <= stop:',
' yield start',
' start += abs(step)']);
};
var defineDownRange = function() {
return Blockly.Python.provideFunction_(
'downRange',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
'(start, stop, step):',
' while start >= stop:',
' yield start',
' start -= abs(step)']);
};
// Arguments are legal Python code (numbers or strings returned by scrub()).
var generateUpDownRange = function(start, end, inc) {
return '(' + start + ' <= ' + end + ') and ' +
defineUpRange() + '(' + start + ', ' + end + ', ' + inc + ') or ' +
defineDownRange() + '(' + start + ', ' + end + ', ' + inc + ')';
};
if (Blockly.isNumber(argument0) && Blockly.isNumber(argument1) &&
Blockly.isNumber(increment)) {
// All parameters are simple numbers.
argument0 = parseFloat(argument0);
argument1 = parseFloat(argument1);
increment = Math.abs(parseFloat(increment));
if (argument0 % 1 === 0 && argument1 % 1 === 0 && increment % 1 === 0) {
// All parameters are integers.
if (argument0 <= argument1) {
// Count up.
argument1++;
if (argument0 == 0 && increment == 1) {
// If starting index is 0, omit it.
range = argument1;
} else {
range = argument0 + ', ' + argument1;
}
// If increment isn't 1, it must be explicit.
if (increment != 1) {
range += ', ' + increment;
}
} else {
// Count down.
argument1--;
range = argument0 + ', ' + argument1 + ', -' + increment;
}
range = 'range(' + range + ')';
} else {
// At least one of the parameters is not an integer.
if (argument0 < argument1) {
range = defineUpRange();
} else {
range = defineDownRange();
}
range += '(' + argument0 + ', ' + argument1 + ', ' + increment + ')';
}
} else {
// Cache non-trivial values to variables to prevent repeated look-ups.
var scrub = function(arg, suffix) {
if (Blockly.isNumber(arg)) {
// Simple number.
arg = parseFloat(arg);
} else if (arg.match(/^\w+$/)) {
// Variable.
arg = 'float(' + arg + ')';
} else {
// It's complicated.
var varName = Blockly.Python.variableDB_.getDistinctName(
variable0 + suffix, Blockly.Variables.NAME_TYPE);
code += varName + ' = float(' + arg + ')\n';
arg = varName;
}
return arg;
};
var startVar = scrub(argument0, '_start');
var endVar = scrub(argument1, '_end');
var incVar = scrub(increment, '_inc');
if (typeof startVar == 'number' && typeof endVar == 'number') {
if (startVar < endVar) {
range = defineUpRange(startVar, endVar, increment);
} else {
range = defineDownRange(startVar, endVar, increment);
}
} else {
// We cannot determine direction statically.
range = generateUpDownRange(startVar, endVar, increment);
}
}
code += 'for ' + variable0 + ' in ' + range + ':\n' + branch;
return code;
};
Blockly.Python['controls_forEach'] = function(block) {
// For each loop.
var variable0 = Blockly.Python.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_RELATIONAL) || '[]';
var branch = Blockly.Python.statementToCode(block, 'DO');
branch = Blockly.Python.addLoopTrap(branch, block.id) ||
Blockly.Python.PASS;
var code = 'for ' + variable0 + ' in ' + argument0 + ':\n' + branch;
return code;
};
Blockly.Python['controls_flow_statements'] = function(block) {
// Flow statements: continue, break.
switch (block.getFieldValue('FLOW')) {
case 'BREAK':
return 'break\n';
case 'CONTINUE':
return 'continue\n';
}
throw 'Unknown flow statement.';
};

View file

@ -1,388 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for math blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.math');
goog.require('Blockly.Python');
// If any new block imports any library, add that library name here.
Blockly.Python.addReservedWords('math,random,Number');
Blockly.Python['math_number'] = function(block) {
// Numeric value.
var code = parseFloat(block.getFieldValue('NUM'));
var order;
if (code == Infinity) {
code = 'float("inf")';
order = Blockly.Python.ORDER_FUNCTION_CALL;
} else if (code == -Infinity) {
code = '-float("inf")';
order = Blockly.Python.ORDER_UNARY_SIGN;
} else {
order = code < 0 ? Blockly.Python.ORDER_UNARY_SIGN :
Blockly.Python.ORDER_ATOMIC;
}
return [code, order];
};
Blockly.Python['math_arithmetic'] = function(block) {
// Basic arithmetic operators, and power.
var OPERATORS = {
'ADD': [' + ', Blockly.Python.ORDER_ADDITIVE],
'MINUS': [' - ', Blockly.Python.ORDER_ADDITIVE],
'MULTIPLY': [' * ', Blockly.Python.ORDER_MULTIPLICATIVE],
'DIVIDE': [' / ', Blockly.Python.ORDER_MULTIPLICATIVE],
'POWER': [' ** ', Blockly.Python.ORDER_EXPONENTIATION]
};
var tuple = OPERATORS[block.getFieldValue('OP')];
var operator = tuple[0];
var order = tuple[1];
var argument0 = Blockly.Python.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'B', order) || '0';
var code = argument0 + operator + argument1;
return [code, order];
// In case of 'DIVIDE', division between integers returns different results
// in Python 2 and 3. However, is not an issue since Blockly does not
// guarantee identical results in all languages. To do otherwise would
// require every operator to be wrapped in a function call. This would kill
// legibility of the generated code.
};
Blockly.Python['math_single'] = function(block) {
// Math operators with single operand.
var operator = block.getFieldValue('OP');
var code;
var arg;
if (operator == 'NEG') {
// Negation is a special case given its different operator precedence.
var code = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_UNARY_SIGN) || '0';
return ['-' + code, Blockly.Python.ORDER_UNARY_SIGN];
}
Blockly.Python.definitions_['import_math'] = 'import math';
if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
arg = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
} else {
arg = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_NONE) || '0';
}
// First, handle cases which generate values that don't need parentheses
// wrapping the code.
switch (operator) {
case 'ABS':
code = 'math.fabs(' + arg + ')';
break;
case 'ROOT':
code = 'math.sqrt(' + arg + ')';
break;
case 'LN':
code = 'math.log(' + arg + ')';
break;
case 'LOG10':
code = 'math.log10(' + arg + ')';
break;
case 'EXP':
code = 'math.exp(' + arg + ')';
break;
case 'POW10':
code = 'math.pow(10,' + arg + ')';
break;
case 'ROUND':
code = 'round(' + arg + ')';
break;
case 'ROUNDUP':
code = 'math.ceil(' + arg + ')';
break;
case 'ROUNDDOWN':
code = 'math.floor(' + arg + ')';
break;
case 'SIN':
code = 'math.sin(' + arg + ' / 180.0 * math.pi)';
break;
case 'COS':
code = 'math.cos(' + arg + ' / 180.0 * math.pi)';
break;
case 'TAN':
code = 'math.tan(' + arg + ' / 180.0 * math.pi)';
break;
}
if (code) {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
// Second, handle cases which generate values that may need parentheses
// wrapping the code.
switch (operator) {
case 'ASIN':
code = 'math.asin(' + arg + ') / math.pi * 180';
break;
case 'ACOS':
code = 'math.acos(' + arg + ') / math.pi * 180';
break;
case 'ATAN':
code = 'math.atan(' + arg + ') / math.pi * 180';
break;
default:
throw 'Unknown math operator: ' + operator;
}
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};
Blockly.Python['math_constant'] = function(block) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
var CONSTANTS = {
'PI': ['math.pi', Blockly.Python.ORDER_MEMBER],
'E': ['math.e', Blockly.Python.ORDER_MEMBER],
'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2',
Blockly.Python.ORDER_MULTIPLICATIVE],
'SQRT2': ['math.sqrt(2)', Blockly.Python.ORDER_MEMBER],
'SQRT1_2': ['math.sqrt(1.0 / 2)', Blockly.Python.ORDER_MEMBER],
'INFINITY': ['float(\'inf\')', Blockly.Python.ORDER_ATOMIC]
};
var constant = block.getFieldValue('CONSTANT');
if (constant != 'INFINITY') {
Blockly.Python.definitions_['import_math'] = 'import math';
}
return CONSTANTS[constant];
};
Blockly.Python['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false.
var number_to_check = Blockly.Python.valueToCode(block, 'NUMBER_TO_CHECK',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var dropdown_property = block.getFieldValue('PROPERTY');
var code;
if (dropdown_property == 'PRIME') {
Blockly.Python.definitions_['import_math'] = 'import math';
Blockly.Python.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
var functionName = Blockly.Python.provideFunction_(
'math_isPrime',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):',
' # https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' # If n is not a number but a string, try parsing it.',
' if not isinstance(n, Number):',
' try:',
' n = float(n)',
' except:',
' return False',
' if n == 2 or n == 3:',
' return True',
' # False if n is negative, is 1, or not whole,' +
' or if n is divisible by 2 or 3.',
' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:',
' return False',
' # Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' for x in range(6, int(math.sqrt(n)) + 2, 6):',
' if n % (x - 1) == 0 or n % (x + 1) == 0:',
' return False',
' return True']);
code = functionName + '(' + number_to_check + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
switch (dropdown_property) {
case 'EVEN':
code = number_to_check + ' % 2 == 0';
break;
case 'ODD':
code = number_to_check + ' % 2 == 1';
break;
case 'WHOLE':
code = number_to_check + ' % 1 == 0';
break;
case 'POSITIVE':
code = number_to_check + ' > 0';
break;
case 'NEGATIVE':
code = number_to_check + ' < 0';
break;
case 'DIVISIBLE_BY':
var divisor = Blockly.Python.valueToCode(block, 'DIVISOR',
Blockly.Python.ORDER_MULTIPLICATIVE);
// If 'divisor' is some code that evals to 0, Python will raise an error.
if (!divisor || divisor == '0') {
return ['False', Blockly.Python.ORDER_ATOMIC];
}
code = number_to_check + ' % ' + divisor + ' == 0';
break;
}
return [code, Blockly.Python.ORDER_RELATIONAL];
};
Blockly.Python['math_change'] = function(block) {
// Add to a variable in place.
Blockly.Python.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
var argument0 = Blockly.Python.valueToCode(block, 'DELTA',
Blockly.Python.ORDER_ADDITIVE) || '0';
var varName = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = (' + varName + ' if isinstance(' + varName +
', Number) else 0) + ' + argument0 + '\n';
};
// Rounding functions have a single operand.
Blockly.Python['math_round'] = Blockly.Python['math_single'];
// Trigonometry functions have a single operand.
Blockly.Python['math_trig'] = Blockly.Python['math_single'];
Blockly.Python['math_on_list'] = function(block) {
// Math functions for lists.
var func = block.getFieldValue('OP');
var list = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_NONE) || '[]';
var code;
switch (func) {
case 'SUM':
code = 'sum(' + list + ')';
break;
case 'MIN':
code = 'min(' + list + ')';
break;
case 'MAX':
code = 'max(' + list + ')';
break;
case 'AVERAGE':
Blockly.Python.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
var functionName = Blockly.Python.provideFunction_(
'math_mean',
// This operation excludes null and values that aren't int or float:',
// math_mean([null, null, "aString", 1, 9]) == 5.0.',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
' localList = [e for e in myList if isinstance(e, Number)]',
' if not localList: return',
' return float(sum(localList)) / len(localList)']);
code = functionName + '(' + list + ')';
break;
case 'MEDIAN':
Blockly.Python.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
var functionName = Blockly.Python.provideFunction_(
'math_median',
// This operation excludes null values:
// math_median([null, null, 1, 3]) == 2.0.
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
' localList = sorted([e for e in myList if isinstance(e, Number)])',
' if not localList: return',
' if len(localList) % 2 == 0:',
' return (localList[len(localList) // 2 - 1] + ' +
'localList[len(localList) // 2]) / 2.0',
' else:',
' return localList[(len(localList) - 1) // 2]']);
code = functionName + '(' + list + ')';
break;
case 'MODE':
var functionName = Blockly.Python.provideFunction_(
'math_modes',
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(some_list):',
' modes = []',
' # Using a lists of [item, count] to keep count rather than dict',
' # to avoid "unhashable" errors when the counted item is ' +
'itself a list or dict.',
' counts = []',
' maxCount = 1',
' for item in some_list:',
' found = False',
' for count in counts:',
' if count[0] == item:',
' count[1] += 1',
' maxCount = max(maxCount, count[1])',
' found = True',
' if not found:',
' counts.append([item, 1])',
' for counted_item, item_count in counts:',
' if item_count == maxCount:',
' modes.append(counted_item)',
' return modes']);
code = functionName + '(' + list + ')';
break;
case 'STD_DEV':
Blockly.Python.definitions_['import_math'] = 'import math';
var functionName = Blockly.Python.provideFunction_(
'math_standard_deviation',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(numbers):',
' n = len(numbers)',
' if n == 0: return',
' mean = float(sum(numbers)) / n',
' variance = sum((x - mean) ** 2 for x in numbers) / n',
' return math.sqrt(variance)']);
code = functionName + '(' + list + ')';
break;
case 'RANDOM':
Blockly.Python.definitions_['import_random'] = 'import random';
code = 'random.choice(' + list + ')';
break;
default:
throw 'Unknown operator: ' + func;
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['math_modulo'] = function(block) {
// Remainder computation.
var argument0 = Blockly.Python.valueToCode(block, 'DIVIDEND',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'DIVISOR',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var code = argument0 + ' % ' + argument1;
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};
Blockly.Python['math_constrain'] = function(block) {
// Constrain a number between two limits.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'LOW',
Blockly.Python.ORDER_NONE) || '0';
var argument2 = Blockly.Python.valueToCode(block, 'HIGH',
Blockly.Python.ORDER_NONE) || 'float(\'inf\')';
var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
argument2 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['math_random_int'] = function(block) {
// Random integer between [X] and [Y].
Blockly.Python.definitions_['import_random'] = 'import random';
var argument0 = Blockly.Python.valueToCode(block, 'FROM',
Blockly.Python.ORDER_NONE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || '0';
var code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['math_random_float'] = function(block) {
// Random fraction between 0 and 1.
Blockly.Python.definitions_['import_random'] = 'import random';
return ['random.random()', Blockly.Python.ORDER_FUNCTION_CALL];
};

View file

@ -1,123 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for procedure blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Python.procedures');
goog.require('Blockly.Python');
Blockly.Python['procedures_defreturn'] = function(block) {
// Define a procedure with a return value.
// First, add a 'global' statement for every variable that is assigned.
var globals = Blockly.Variables.allVariables(block);
for (var i = globals.length - 1; i >= 0; i--) {
var varName = globals[i];
if (block.arguments_.indexOf(varName) == -1) {
globals[i] = Blockly.Python.variableDB_.getName(varName,
Blockly.Variables.NAME_TYPE);
} else {
// This variable is actually a parameter name. Do not include it in
// the list of globals, thus allowing it be of local scope.
globals.splice(i, 1);
}
}
globals = globals.length ? ' global ' + globals.join(', ') + '\n' : '';
var funcName = Blockly.Python.variableDB_.getName(block.getFieldValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var branch = Blockly.Python.statementToCode(block, 'STACK');
if (Blockly.Python.STATEMENT_PREFIX) {
branch = Blockly.Python.prefixLines(
Blockly.Python.STATEMENT_PREFIX.replace(/%1/g,
'\'' + block.id + '\''), Blockly.Python.INDENT) + branch;
}
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'"' + block.id + '"') + branch;
}
var returnValue = Blockly.Python.valueToCode(block, 'RETURN',
Blockly.Python.ORDER_NONE) || '';
if (returnValue) {
returnValue = ' return ' + returnValue + '\n';
} else if (!branch) {
branch = Blockly.Python.PASS;
}
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Python.variableDB_.getName(block.arguments_[x],
Blockly.Variables.NAME_TYPE);
}
var code = 'def ' + funcName + '(' + args.join(', ') + '):\n' +
globals + branch + returnValue;
code = Blockly.Python.scrub_(block, code);
Blockly.Python.definitions_[funcName] = code;
return null;
};
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
Blockly.Python['procedures_defnoreturn'] =
Blockly.Python['procedures_defreturn'];
Blockly.Python['procedures_callreturn'] = function(block) {
// Call a procedure with a return value.
var funcName = Blockly.Python.variableDB_.getName(block.getFieldValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Python.valueToCode(block, 'ARG' + x,
Blockly.Python.ORDER_NONE) || 'None';
}
var code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['procedures_callnoreturn'] = function(block) {
// Call a procedure with no return value.
var funcName = Blockly.Python.variableDB_.getName(block.getFieldValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Python.valueToCode(block, 'ARG' + x,
Blockly.Python.ORDER_NONE) || 'None';
}
var code = funcName + '(' + args.join(', ') + ')\n';
return code;
};
Blockly.Python['procedures_ifreturn'] = function(block) {
// Conditionally return value from a procedure.
var condition = Blockly.Python.valueToCode(block, 'CONDITION',
Blockly.Python.ORDER_NONE) || 'False';
var code = 'if ' + condition + ':\n';
if (block.hasReturnValue_) {
var value = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || 'None';
code += ' return ' + value + '\n';
} else {
code += ' return\n';
}
return code;
};

View file

@ -1,262 +0,0 @@
/**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for text blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.texts');
goog.require('Blockly.Python');
Blockly.Python['text'] = function(block) {
// Text value.
var code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['text_join'] = function(block) {
// Create a string made up of any number of elements of any type.
//Should we allow joining by '-' or ',' or any other characters?
var code;
if (block.itemCount_ == 0) {
return ['\'\'', Blockly.Python.ORDER_ATOMIC];
} else if (block.itemCount_ == 1) {
var argument0 = Blockly.Python.valueToCode(block, 'ADD0',
Blockly.Python.ORDER_NONE) || '\'\'';
code = 'str(' + argument0 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (block.itemCount_ == 2) {
var argument0 = Blockly.Python.valueToCode(block, 'ADD0',
Blockly.Python.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Python.valueToCode(block, 'ADD1',
Blockly.Python.ORDER_NONE) || '\'\'';
var code = 'str(' + argument0 + ') + str(' + argument1 + ')';
return [code, Blockly.Python.ORDER_UNARY_SIGN];
} else {
var code = [];
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.Python.valueToCode(block, 'ADD' + n,
Blockly.Python.ORDER_NONE) || '\'\'';
}
var tempVar = Blockly.Python.variableDB_.getDistinctName('temp_value',
Blockly.Variables.NAME_TYPE);
code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
code.join(', ') + ']])';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
};
Blockly.Python['text_append'] = function(block) {
// Append to a variable in place.
var varName = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
return varName + ' = str(' + varName + ') + str(' + argument0 + ')\n';
};
Blockly.Python['text_length'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '\'\'';
return ['len(' + argument0 + ')', Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_isEmpty'] = function(block) {
// Is the string null or array empty?
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '\'\'';
var code = 'not len(' + argument0 + ')';
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.Python['text_indexOf'] = function(block) {
// Search the text for a substring.
// Should we allow for non-case sensitive???
var operator = block.getFieldValue('END') == 'FIRST' ? 'find' : 'rfind';
var argument0 = Blockly.Python.valueToCode(block, 'FIND',
Blockly.Python.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_charAt'] = function(block) {
// Get letter at index.
// Note: Until January 2013 this block did not have the WHERE input.
var where = block.getFieldValue('WHERE') || 'FROM_START';
var at = Blockly.Python.valueToCode(block, 'AT',
Blockly.Python.ORDER_UNARY_SIGN) || '1';
var text = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
switch (where) {
case 'FIRST':
var code = text + '[0]';
return [code, Blockly.Python.ORDER_MEMBER];
case 'LAST':
var code = text + '[-1]';
return [code, Blockly.Python.ORDER_MEMBER];
case 'FROM_START':
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at = 'int(' + at + ' - 1)';
}
var code = text + '[' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
case 'FROM_END':
var code = text + '[-' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
case 'RANDOM':
Blockly.Python.definitions_['import_random'] = 'import random';
var functionName = Blockly.Python.provideFunction_(
'text_random_letter',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(text):',
' x = int(random.random() * len(text))',
' return text[x];']);
code = functionName + '(' + text + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
throw 'Unhandled option (text_charAt).';
};
Blockly.Python['text_getSubstring'] = function(block) {
// Get substring.
var text = Blockly.Python.valueToCode(block, 'STRING',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var where1 = block.getFieldValue('WHERE1');
var where2 = block.getFieldValue('WHERE2');
var at1 = Blockly.Python.valueToCode(block, 'AT1',
Blockly.Python.ORDER_ADDITIVE) || '1';
var at2 = Blockly.Python.valueToCode(block, 'AT2',
Blockly.Python.ORDER_ADDITIVE) || '1';
if (where1 == 'FIRST' || (where1 == 'FROM_START' && at1 == '1')) {
at1 = '';
} else if (where1 == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at1)) {
// If the index is a naked number, decrement it right now.
at1 = parseInt(at1, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at1 = 'int(' + at1 + ' - 1)';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at1)) {
at1 = -parseInt(at1, 10);
} else {
at1 = '-int(' + at1 + ')';
}
}
if (where2 == 'LAST' || (where2 == 'FROM_END' && at2 == '1')) {
at2 = '';
} else if (where1 == 'FROM_START') {
if (Blockly.isNumber(at2)) {
at2 = parseInt(at2, 10);
} else {
at2 = 'int(' + at2 + ')';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at2)) {
// If the index is a naked number, increment it right now.
at2 = 1 - parseInt(at2, 10);
if (at2 == 0) {
at2 = '';
}
} else {
// If the index is dynamic, increment it in code.
// Add special case for -0.
Blockly.Python.definitions_['import_sys'] = 'import sys';
at2 = 'int(1 - ' + at2 + ') or sys.maxsize';
}
}
var code = text + '[' + at1 + ' : ' + at2 + ']';
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_changeCase'] = function(block) {
// Change capitalization.
var OPERATORS = {
'UPPERCASE': '.upper()',
'LOWERCASE': '.lower()',
'TITLECASE': '.title()'
};
var operator = OPERATORS[block.getFieldValue('CASE')];
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = argument0 + operator;
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_trim'] = function(block) {
// Trim spaces.
var OPERATORS = {
'LEFT': '.lstrip()',
'RIGHT': '.rstrip()',
'BOTH': '.strip()'
};
var operator = OPERATORS[block.getFieldValue('MODE')];
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = argument0 + operator;
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_print'] = function(block) {
// Print statement.
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
return 'print(' + argument0 + ')\n';
};
Blockly.Python['text_prompt_ext'] = function(block) {
// Prompt function.
var functionName = Blockly.Python.provideFunction_(
'text_prompt',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(msg):',
' try:',
' return raw_input(msg)',
' except NameError:',
' return input(msg)']);
if (block.getField('TEXT')) {
// Internal message.
var msg = Blockly.Python.quote_(block.getFieldValue('TEXT'));
} else {
// External message.
var msg = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
}
var code = functionName + '(' + msg + ')';
var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
if (toNumber) {
code = 'float(' + code + ')';
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_prompt'] = Blockly.Python['text_prompt_ext'];

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.2.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 48 48" style="enable-background:new 0 0 48 48;" xml:space="preserve">
<style type="text/css">
.st0{fill:#CC9823;}
.st1{fill:#FFFFFF;}
</style>
<path class="st0" d="M24,43.4H11.1c-1.8,0-3.2-1.4-3.2-3.2s1.4-3.2,3.2-3.2H24c5.3,0,9.7-4.3,9.7-9.7c0-5.3-4.3-9.7-9.7-9.7h-9.7
c-1.8,0-3.2-1.4-3.2-3.2s1.4-3.2,3.2-3.2H24c8.9,0,16.2,7.2,16.2,16.2C40.2,36.1,32.9,43.4,24,43.4z"/>
<path class="st0" d="M17.5,24c-0.8,0-1.7-0.3-2.3-0.9l-6.5-6.5c-1.3-1.3-1.3-3.3,0-4.6l6.5-6.5c1.3-1.3,3.3-1.3,4.6,0
c1.3,1.3,1.3,3.3,0,4.6l-4.2,4.2l4.2,4.2c1.3,1.3,1.3,3.3,0,4.6C19.2,23.7,18.4,24,17.5,24z"/>
<path class="st1" d="M24,42.6H11.1c-1.3,0-2.4-1.1-2.4-2.4s1.1-2.4,2.4-2.4H24c5.8,0,10.5-4.7,10.5-10.5c0-5.8-4.7-10.5-10.5-10.5
h-9.7c-1.3,0-2.4-1.1-2.4-2.4s1.1-2.4,2.4-2.4H24c8.5,0,15.3,6.9,15.3,15.3S32.5,42.6,24,42.6z"/>
<path class="st1" d="M17.5,23.2c-0.6,0-1.2-0.2-1.7-0.7L9.4,16c-0.9-0.9-0.9-2.5,0-3.4l6.5-6.5c0.9-0.9,2.5-0.9,3.4,0
c0.9,0.9,0.9,2.5,0,3.4l-4.7,4.7l4.7,4.7c0.9,0.9,0.9,2.5,0,3.4C18.8,23,18.2,23.2,17.5,23.2z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.2.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 48 48" style="enable-background:new 0 0 48 48;" xml:space="preserve">
<style type="text/css">
.st0{fill:#2BB673;stroke:#25995F;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;}
.st1{fill:#25995F;stroke:#25995F;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;}
</style>
<g>
<g>
<path class="st0" d="M39.8,11.1v17.5c0,0.3-0.1,0.7-0.4,0.9c-2.2,1.9-5,3-7.9,3c-2.9,0-5.7-1.1-7.9-3c-1.8-1.6-4.1-2.4-6.4-2.4
c-2.1,0-4.2,0.7-5.9,2.1v11.6c0,0.7-0.5,1.2-1.2,1.2c-0.7,0-1.2-0.5-1.2-1.2V11.1c0-0.5,0.3-0.9,0.7-1.1c2.2-1.8,4.9-2.7,7.6-2.7
c2.9,0,5.7,1,7.9,3c1.8,1.5,4.1,2.4,6.4,2.4s4.6-0.9,6.4-2.4c0.3-0.3,0.8-0.4,1.2-0.2C39.5,10.3,39.8,10.7,39.8,11.1z"/>
</g>
<path class="st1" d="M10,42L10,42c-0.6,0-1.1-0.5-1.1-1.1V7.5c0-0.6,0.5-1.1,1.1-1.1h0c0.6,0,1.1,0.5,1.1,1.1v33.4
C11.1,41.5,10.6,42,10,42z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.2.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 76 76" style="enable-background:new 0 0 76 76;" xml:space="preserve">
<style type="text/css">
.st0{fill:#308BA0;}
.st1{fill:#FFFFFF;}
</style>
<g>
<path class="st0" d="M17.2,33.1c0-3-2.4-5.4-5.4-5.4h-1.4c-3,0-5.4,2.4-5.4,5.4v10.8c0,3,2.4,5.4,5.4,5.4h1.4c3,0,5.4-2.4,5.4-5.4
V33.1z"/>
<path class="st1" d="M15.8,33.1c0-2.2-1.8-4.1-4.1-4.1h-1.4c-2.2,0-4.1,1.8-4.1,4.1v10.8c0,2.2,1.8,4.1,4.1,4.1h1.4
c2.2,0,4.1-1.8,4.1-4.1V33.1z"/>
</g>
<g>
<path class="st0" d="M30.7,33.1c0-3-2.4-5.4-5.4-5.4h-1.4c-3,0-5.4,2.4-5.4,5.4v10.8c0,3,2.4,5.4,5.4,5.4h1.4c3,0,5.4-2.4,5.4-5.4
V33.1z"/>
<path class="st1" d="M29.3,33.1c0-2.2-1.8-4.1-4.1-4.1h-1.4c-2.2,0-4.1,1.8-4.1,4.1v10.8c0,2.2,1.8,4.1,4.1,4.1h1.4
c2.2,0,4.1-1.8,4.1-4.1V33.1z"/>
</g>
<g id="Layer_2">
<g id="fd">
<g>
<path class="st0" d="M32.2,32.2c0-1.2,0.4-2.3,1.2-3.1c1.1-0.9,2.5-1.4,4-1.2l3.5,0.6c0.7,0.1,1.4-0.1,1.7-0.4
c0.2-0.2,0.4-0.5,0.4-0.8c0-0.1-0.4-5.7-0.4-5.7c0-0.1,0-0.4,0-0.6c0-2.3,1.6-4.9,6.1-4.9c4.8,0,17,14.1,20.7,18.6
c1,0.9,1.5,2.1,1.5,3.4c0,1.3-0.5,2.5-1.5,3.4C66.8,44.7,54.2,60,48.8,60c-1.9,0-3.4-0.4-4.5-1.3c-1-0.8-1.6-2.1-1.6-3.5l0,0
c0-0.2,0-0.5,0-0.8l0.3-5.4c0-0.1,0-0.2,0-0.3c0-0.3-0.1-0.6-0.4-0.8c-0.4-0.4-1-0.5-1.8-0.4l-3.5,0.6c-1.6,0.2-2.9-0.3-4-1.2
c-0.9-0.8-1.3-1.9-1.3-3.1L32.2,32.2L32.2,32.2z"/>
</g>
<g>
<path class="st1" d="M68.5,40.5c1.5-1.4,1.5-3.6,0-5c0,0-15.2-18.2-19.8-18.2c-3.4,0-4.9,1.8-4.7,4.1l0.3,5.5
c0.2,1.9-1.4,3.2-3.6,3l-3.5-0.6c-2.2-0.2-3.7,0.9-3.7,2.8v12.2c0,1.9,1.5,3,3.7,2.8l3.5-0.6c2.2-0.2,3.8,1.1,3.6,3l-0.3,5.5
c-0.3,2.2,0.9,4.1,4.7,4.1C53.9,58.7,68.5,40.5,68.5,40.5z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -5,50 +5,15 @@
<title>Blockly Playground</title>
<script src="../blockly_uncompressed.js"></script>
<script src="../generators/javascript.js"></script>
<script src="../generators/javascript/logic.js"></script>
<script src="../generators/javascript/loops.js"></script>
<script src="../generators/javascript/control.js"></script>
<script src="../generators/javascript/math.js"></script>
<script src="../generators/javascript/text.js"></script>
<script src="../generators/javascript/lists.js"></script>
<script src="../generators/javascript/colour.js"></script>
<script src="../generators/javascript/variables.js"></script>
<script src="../generators/javascript/procedures.js"></script>
<script src="../generators/php.js"></script>
<script src="../generators/php/logic.js"></script>
<script src="../generators/php/loops.js"></script>
<script src="../generators/php/math.js"></script>
<script src="../generators/php/text.js"></script>
<script src="../generators/php/lists.js"></script>
<script src="../generators/php/colour.js"></script>
<script src="../generators/php/variables.js"></script>
<script src="../generators/php/procedures.js"></script>
<script src="../generators/python.js"></script>
<script src="../generators/python/logic.js"></script>
<script src="../generators/python/loops.js"></script>
<script src="../generators/python/math.js"></script>
<script src="../generators/python/text.js"></script>
<script src="../generators/python/lists.js"></script>
<script src="../generators/python/colour.js"></script>
<script src="../generators/python/variables.js"></script>
<script src="../generators/python/procedures.js"></script>
<script src="../generators/dart.js"></script>
<script src="../generators/dart/logic.js"></script>
<script src="../generators/dart/loops.js"></script>
<script src="../generators/dart/math.js"></script>
<script src="../generators/dart/text.js"></script>
<script src="../generators/dart/lists.js"></script>
<script src="../generators/dart/colour.js"></script>
<script src="../generators/dart/variables.js"></script>
<script src="../generators/dart/procedures.js"></script>
<script src="../generators/javascript/motion.js"></script>
<script src="../generators/javascript/event.js"></script>
<script src="../msg/messages.js"></script>
<script src="../blocks/logic.js"></script>
<script src="../blocks/loops.js"></script>
<script src="../blocks/math.js"></script>
<script src="../blocks/text.js"></script>
<script src="../blocks/lists.js"></script>
<script src="../blocks/colour.js"></script>
<script src="../blocks/variables.js"></script>
<script src="../blocks/procedures.js"></script>
<script src="../blocks_horizontal/event.js"></script>
<script src="../blocks_horizontal/control.js"></script>
<script src="../blocks_horizontal/motion.js"></script>
<script>
'use strict';
// Depending on the URL argument, render as LTR or RTL.
@ -57,30 +22,26 @@ var workspace = null;
function start() {
var toolbox = document.getElementById('toolbox');
workspace = Blockly.inject('blocklyDiv',
{comments: true,
disable: true,
collapse: true,
grid:
{spacing: 25,
length: 3,
colour: '#ccc',
snap: true},
maxBlocks: Infinity,
media: '../media/',
readOnly: false,
rtl: rtl,
scrollbars: true,
toolbox: toolbox,
zoom:
{controls: true,
wheel: true,
startScale: 1.0,
maxScale: 4,
minScale: .25,
scaleSpeed: 1.1
},
});
workspace = Blockly.inject('blocklyDiv', {
comments: false,
disable: false,
collapse: false,
maxBlocks: Infinity,
media: '../media/',
readOnly: false,
rtl: rtl,
scrollbars: true,
toolbox: toolbox,
trashcan: true,
zoom: {
controls: true,
wheel: false,
startScale: 1.0,
maxScale: 4,
minScale: 0.25,
scaleSpeed: 1.1
},
});
}
function toXml() {
@ -101,68 +62,6 @@ function toCode(lang) {
var output = document.getElementById('importExport');
output.value = Blockly[lang].workspaceToCode(workspace);
}
function airstrike(n) {
var prototypes = [];
var toolbox = document.getElementById('toolbox');
var blocks = toolbox.getElementsByTagName('block');
for (var i = 0, block; block = blocks[i]; i++) {
prototypes.push(block.getAttribute('type'));
}
for (var i = 0; i < n; i++) {
var prototype = prototypes[Math.floor(Math.random() * prototypes.length)];
var block = workspace.newBlock(prototype);
block.initSvg();
block.getSvgRoot().setAttribute('transform', 'translate(' +
Math.round(Math.random() * 450 + 40) + ', ' +
Math.round(Math.random() * 600 + 40) + ')');
block.render();
}
}
function spaghetti(n) {
var xml = spaghettiXml;
for(var i = 0; i < n; i++) {
xml = xml.replace(/(<(statement|next)( name="DO0")?>)<\//g,
'$1' + spaghettiXml + '</');
}
xml = '<xml xmlns="http://www.w3.org/1999/xhtml">' + xml + '</xml>';
var dom = Blockly.Xml.textToDom(xml);
console.time('Spaghetti domToWorkspace');
Blockly.Xml.domToWorkspace(workspace, dom);
console.timeEnd('Spaghetti domToWorkspace');
}
var spaghettiXml = [
' <block type="controls_if">',
' <value name="IF0">',
' <block type="logic_compare">',
' <field name="OP">EQ</field>',
' <value name="A">',
' <block type="math_arithmetic">',
' <field name="OP">MULTIPLY</field>',
' <value name="A">',
' <block type="math_number">',
' <field name="NUM">6</field>',
' </block>',
' </value>',
' <value name="B">',
' <block type="math_number">',
' <field name="NUM">7</field>',
' </block>',
' </value>',
' </block>',
' </value>',
' <value name="B">',
' <block type="math_number">',
' <field name="NUM">42</field>',
' </block>',
' </value>',
' </block>',
' </value>',
' <statement name="DO0"></statement>',
' <next></next>',
' </block>'].join('\n');
</script>
<style>
@ -207,310 +106,20 @@ h1 {
<div id="blocklyDiv"></div>
<xml id="toolbox" style="display: none">
<category name="Logic" colour="210">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="logic_operation"></block>
<block type="logic_negate"></block>
<block type="logic_boolean"></block>
<block type="logic_null" disabled="true"></block>
<block type="logic_ternary"></block>
</category>
<category name="Loops" colour="120">
<block type="controls_repeat_ext">
<value name="TIMES">
<shadow type="math_number">
<field name="NUM">10</field>
</shadow>
</value>
</block>
<block type="controls_repeat" disabled="true"></block>
<block type="controls_whileUntil"></block>
<block type="controls_for">
<value name="FROM">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
<value name="TO">
<shadow type="math_number">
<field name="NUM">10</field>
</shadow>
</value>
<value name="BY">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
</block>
<block type="controls_forEach"></block>
<block type="controls_flow_statements"></block>
</category>
<category name="Math" colour="230">
<block type="math_number" gap="32"></block>
<block type="math_arithmetic">
<value name="A">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
<value name="B">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
</block>
<block type="math_single">
<value name="NUM">
<shadow type="math_number">
<field name="NUM">9</field>
</shadow>
</value>
</block>
<block type="math_trig">
<value name="NUM">
<shadow type="math_number">
<field name="NUM">45</field>
</shadow>
</value>
</block>
<block type="math_constant"></block>
<block type="math_number_property">
<value name="NUMBER_TO_CHECK">
<shadow type="math_number">
<field name="NUM">0</field>
</shadow>
</value>
</block>
<block type="math_change">
<value name="DELTA">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
</block>
<block type="math_round">
<value name="NUM">
<shadow type="math_number">
<field name="NUM">3.1</field>
</shadow>
</value>
</block>
<block type="math_on_list"></block>
<block type="math_modulo">
<value name="DIVIDEND">
<shadow type="math_number">
<field name="NUM">64</field>
</shadow>
</value>
<value name="DIVISOR">
<shadow type="math_number">
<field name="NUM">10</field>
</shadow>
</value>
</block>
<block type="math_constrain">
<value name="VALUE">
<shadow type="math_number">
<field name="NUM">50</field>
</shadow>
</value>
<value name="LOW">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
<value name="HIGH">
<shadow type="math_number">
<field name="NUM">100</field>
</shadow>
</value>
</block>
<block type="math_random_int">
<value name="FROM">
<shadow type="math_number">
<field name="NUM">1</field>
</shadow>
</value>
<value name="TO">
<shadow type="math_number">
<field name="NUM">100</field>
</shadow>
</value>
</block>
<block type="math_random_float"></block>
</category>
<category name="Text" colour="160">
<block type="text"></block>
<block type="text_join"></block>
<block type="text_append">
<value name="TEXT">
<shadow type="text"></shadow>
</value>
</block>
<block type="text_length">
<value name="VALUE">
<shadow type="text">
<field name="TEXT">abc</field>
</shadow>
</value>
</block>
<block type="text_isEmpty">
<value name="VALUE">
<shadow type="text">
<field name="TEXT"></field>
</shadow>
</value>
</block>
<block type="text_indexOf">
<value name="VALUE">
<block type="variables_get">
<field name="VAR">text</field>
</block>
</value>
<value name="FIND">
<shadow type="text">
<field name="TEXT">abc</field>
</shadow>
</value>
</block>
<block type="text_charAt">
<value name="VALUE">
<block type="variables_get">
<field name="VAR">text</field>
</block>
</value>
</block>
<block type="text_getSubstring">
<value name="STRING">
<block type="variables_get">
<field name="VAR">text</field>
</block>
</value>
</block>
<block type="text_changeCase">
<value name="TEXT">
<shadow type="text">
<field name="TEXT">abc</field>
</shadow>
</value>
</block>
<block type="text_trim">
<value name="TEXT">
<shadow type="text">
<field name="TEXT">abc</field>
</shadow>
</value>
</block>
<block type="text_print">
<value name="TEXT">
<shadow type="text">
<field name="TEXT">abc</field>
</shadow>
</value>
</block>
<block type="text_prompt_ext">
<value name="TEXT">
<shadow type="text">
<field name="TEXT">abc</field>
</shadow>
</value>
</block>
</category>
<category name="Lists" colour="260">
<block type="lists_create_with">
<mutation items="0"></mutation>
</block>
<block type="lists_create_with"></block>
<block type="lists_repeat">
<value name="NUM">
<shadow type="math_number">
<field name="NUM">5</field>
</shadow>
</value>
</block>
<block type="lists_length"></block>
<block type="lists_isEmpty"></block>
<block type="lists_indexOf">
<value name="VALUE">
<block type="variables_get">
<field name="VAR">list</field>
</block>
</value>
</block>
<block type="lists_getIndex">
<value name="VALUE">
<block type="variables_get">
<field name="VAR">list</field>
</block>
</value>
</block>
<block type="lists_setIndex">
<value name="LIST">
<block type="variables_get">
<field name="VAR">list</field>
</block>
</value>
</block>
<block type="lists_getSublist">
<value name="LIST">
<block type="variables_get">
<field name="VAR">list</field>
</block>
</value>
</block>
<block type="lists_split">
<value name="DELIM">
<shadow type="text">
<field name="TEXT">,</field>
</shadow>
</value>
</block>
</category>
<category name="Colour" colour="20">
<block type="colour_picker"></block>
<block type="colour_random"></block>
<block type="colour_rgb">
<value name="RED">
<shadow type="math_number">
<field name="NUM">100</field>
</shadow>
</value>
<value name="GREEN">
<shadow type="math_number">
<field name="NUM">50</field>
</shadow>
</value>
<value name="BLUE">
<shadow type="math_number">
<field name="NUM">0</field>
</shadow>
</value>
</block>
<block type="colour_blend">
<value name="COLOUR1">
<shadow type="colour_picker">
<field name="COLOUR">#ff0000</field>
</shadow>
</value>
<value name="COLOUR2">
<shadow type="colour_picker">
<field name="COLOUR">#3333ff</field>
</shadow>
</value>
<value name="RATIO">
<shadow type="math_number">
<field name="NUM">0.5</field>
</shadow>
</value>
</block>
</category>
<sep></sep>
<category name="Variables" colour="330" custom="VARIABLE"></category>
<category name="Functions" colour="290" custom="PROCEDURE"></category>
<block type="event_whenflagclicked"></block>
<block type="motion_moveright"></block>
<!-- <block type="control_repeat"></block> -->
<block type="control_forever"></block>
<block type="control_repeat">
<value name="TIMES">
<shadow type="math_number">
<field name="NUM">10</field>
</shadow>
</value>
</block>
</xml>
<h1>Blockly Playground</h1>
<h1>Weeee!</h1>
<p><a href="javascript:void(workspace.setVisible(true))">Show</a>
- <a href="javascript:void(workspace.setVisible(false))">Hide</a></p>
@ -529,22 +138,9 @@ h1 {
<input type="button" value="Import from XML" onclick="fromXml()">
<br>
<input type="button" value="To JavaScript" onclick="toCode('JavaScript')">
&nbsp;
<input type="button" value="To Python" onclick="toCode('Python')">
&nbsp;
<input type="button" value="To PHP" onclick="toCode('PHP')">
&nbsp;
<input type="button" value="To Dart" onclick="toCode('Dart')">
<br>
<textarea id="importExport" style="width: 26%; height: 12em"></textarea>
</p>
<hr>
<p>
Stress test:
<input type="button" value="Airstrike!" onclick="airstrike(100)">
<input type="button" value="Spaghetti!" onclick="spaghetti(8)">
</p>
</body>
</html>