openscad.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://blockly.googlecode.com/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Helper functions for generating OpenSCAD for blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.OpenSCAD');
  26. goog.require('Blockly.Generator');
  27. Blockly.OpenSCAD = new Blockly.Generator('OpenSCAD');
  28. /**
  29. * List of illegal variable names.
  30. * This is not intended to be a security feature. Blockly is 100% client-side,
  31. * so bypassing this list is trivial. This is intended to prevent users from
  32. * accidentally clobbering a built-in object or function.
  33. * @private
  34. */
  35. Blockly.OpenSCAD.addReservedWords(
  36. 'Blockly,' + // In case JS is evaled in the current window.
  37. // OpenSCAD reserved words
  38. 'break,delete,for,function,if,return,intersection_for,union,difference,intersection,module,' +
  39. 'rotate,translate,mirror,minkowski,scale,resize,hull,use,assign,color,linear_extrude,rotate_extrude,twist-rotate-extrude' +
  40. 'import,sphere,cylinder,cube,square,circle,torus,twistytorus,' +
  41. 'null,true,false,undef' +
  42. // https://developer.mozilla.org/en/DOM/window
  43. 'applicationCache,closed,Components,content,_content,controllers,crypto,defaultStatus,dialogArguments,directories,document,frameElement,frames,fullScreen,globalStorage,history,innerHeight,innerWidth,length,location,locationbar,localStorage,menubar,messageManager,mozAnimationStartTime,mozInnerScreenX,mozInnerScreenY,mozPaintCount,name,navigator,opener,outerHeight,outerWidth,pageXOffset,pageYOffset,parent,performance,personalbar,pkcs11,returnValue,screen,screenX,screenY,scrollbars,scrollMaxX,scrollMaxY,scrollX,scrollY,self,sessionStorage,sidebar,status,statusbar,toolbar,top,URL,window,' +
  44. 'addEventListener,alert,atob,back,blur,btoa,captureEvents,clearImmediate,clearInterval,clearTimeout,close,confirm,disableExternalCapture,dispatchEvent,dump,enableExternalCapture,escape,find,focus,forward,GeckoActiveXObject,getAttention,getAttentionWithCycleCount,getComputedStyle,getSelection,home,matchMedia,maximize,minimize,moveBy,moveTo,mozRequestAnimationFrame,open,openDialog,postMessage,print,prompt,QueryInterface,releaseEvents,removeEventListener,resizeBy,resizeTo,restore,routeEvent,scroll,scrollBy,scrollByLines,scrollByPages,scrollTo,setCursor,setImmediate,setInterval,setResizable,setTimeout,showModalDialog,sizeToContent,stop,unescape,updateCommands,XPCNativeWrapper,XPCSafeJSObjectWrapper,' +
  45. 'onabort,onbeforeunload,onblur,onchange,onclick,onclose,oncontextmenu,ondevicemotion,ondeviceorientation,ondragdrop,onerror,onfocus,onhashchange,onkeydown,onkeypress,onkeyup,onload,onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmozbeforepaint,onpaint,onpopstate,onreset,onresize,onscroll,onselect,onsubmit,onunload,onpageshow,onpagehide,' +
  46. 'Image,Option,Worker,' +
  47. // https://developer.mozilla.org/en/Gecko_DOM_Reference
  48. 'Event,Range,File,FileReader,Blob,BlobBuilder,' +
  49. 'Attr,CDATASection,CharacterData,Comment,console,DocumentFragment,DocumentType,DomConfiguration,DOMError,DOMErrorHandler,DOMException,DOMImplementation,DOMImplementationList,DOMImplementationRegistry,DOMImplementationSource,DOMLocator,DOMObject,DOMString,DOMStringList,DOMTimeStamp,DOMUserData,Entity,EntityReference,MediaQueryList,MediaQueryListListener,NameList,NamedNodeMap,Node,NodeFilter,NodeIterator,NodeList,Notation,Plugin,PluginArray,ProcessingInstruction,SharedWorker,Text,TimeRanges,Treewalker,TypeInfo,UserDataHandler,Worker,WorkerGlobalScope,' +
  50. 'HTMLDocument,HTMLElement,HTMLAnchorElement,HTMLAppletElement,HTMLAudioElement,HTMLAreaElement,HTMLBaseElement,HTMLBaseFontElement,HTMLBodyElement,HTMLBRElement,HTMLButtonElement,HTMLCanvasElement,HTMLDirectoryElement,HTMLDivElement,HTMLDListElement,HTMLEmbedElement,HTMLFieldSetElement,HTMLFontElement,HTMLFormElement,HTMLFrameElement,HTMLFrameSetElement,HTMLHeadElement,HTMLHeadingElement,HTMLHtmlElement,HTMLHRElement,HTMLIFrameElement,HTMLImageElement,HTMLInputElement,HTMLKeygenElement,HTMLLabelElement,HTMLLIElement,HTMLLinkElement,HTMLMapElement,HTMLMenuElement,HTMLMetaElement,HTMLModElement,HTMLObjectElement,HTMLOListElement,HTMLOptGroupElement,HTMLOptionElement,HTMLOutputElement,HTMLParagraphElement,HTMLParamElement,HTMLPreElement,HTMLQuoteElement,HTMLScriptElement,HTMLSelectElement,HTMLSourceElement,HTMLSpanElement,HTMLStyleElement,HTMLTableElement,HTMLTableCaptionElement,HTMLTableCellElement,HTMLTableDataCellElement,HTMLTableHeaderCellElement,HTMLTableColElement,HTMLTableRowElement,HTMLTableSectionElement,HTMLTextAreaElement,HTMLTimeElement,HTMLTitleElement,HTMLTrackElement,HTMLUListElement,HTMLUnknownElement,HTMLVideoElement,' +
  51. 'HTMLCanvasElement,CanvasRenderingContext2D,CanvasGradient,CanvasPattern,TextMetrics,ImageData,CanvasPixelArray,HTMLAudioElement,HTMLVideoElement,NotifyAudioAvailableEvent,HTMLCollection,HTMLAllCollection,HTMLFormControlsCollection,HTMLOptionsCollection,HTMLPropertiesCollection,DOMTokenList,DOMSettableTokenList,DOMStringMap,RadioNodeList,' +
  52. 'SVGDocument,SVGElement,SVGAElement,SVGAltGlyphElement,SVGAltGlyphDefElement,SVGAltGlyphItemElement,SVGAnimationElement,SVGAnimateElement,SVGAnimateColorElement,SVGAnimateMotionElement,SVGAnimateTransformElement,SVGSetElement,SVGCircleElement,SVGClipPathElement,SVGColorProfileElement,SVGCursorElement,SVGDefsElement,SVGDescElement,SVGEllipseElement,SVGFilterElement,SVGFilterPrimitiveStandardAttributes,SVGFEBlendElement,SVGFEColorMatrixElement,SVGFEComponentTransferElement,SVGFECompositeElement,SVGFEConvolveMatrixElement,SVGFEDiffuseLightingElement,SVGFEDisplacementMapElement,SVGFEDistantLightElement,SVGFEFloodElement,SVGFEGaussianBlurElement,SVGFEImageElement,SVGFEMergeElement,SVGFEMergeNodeElement,SVGFEMorphologyElement,SVGFEOffsetElement,SVGFEPointLightElement,SVGFESpecularLightingElement,SVGFESpotLightElement,SVGFETileElement,SVGFETurbulenceElement,SVGComponentTransferFunctionElement,SVGFEFuncRElement,SVGFEFuncGElement,SVGFEFuncBElement,SVGFEFuncAElement,SVGFontElement,SVGFontFaceElement,SVGFontFaceFormatElement,SVGFontFaceNameElement,SVGFontFaceSrcElement,SVGFontFaceUriElement,SVGForeignObjectElement,SVGGElement,SVGGlyphElement,SVGGlyphRefElement,SVGGradientElement,SVGLinearGradientElement,SVGRadialGradientElement,SVGHKernElement,SVGImageElement,SVGLineElement,SVGMarkerElement,SVGMaskElement,SVGMetadataElement,SVGMissingGlyphElement,SVGMPathElement,SVGPathElement,SVGPatternElement,SVGPolylineElement,SVGPolygonElement,SVGRectElement,SVGScriptElement,SVGStopElement,SVGStyleElement,SVGSVGElement,SVGSwitchElement,SVGSymbolElement,SVGTextElement,SVGTextPathElement,SVGTitleElement,SVGTRefElement,SVGTSpanElement,SVGUseElement,SVGViewElement,SVGVKernElement,' +
  53. 'SVGAngle,SVGColor,SVGICCColor,SVGElementInstance,SVGElementInstanceList,SVGLength,SVGLengthList,SVGMatrix,SVGNumber,SVGNumberList,SVGPaint,SVGPoint,SVGPointList,SVGPreserveAspectRatio,SVGRect,SVGStringList,SVGTransform,SVGTransformList,' +
  54. 'SVGAnimatedAngle,SVGAnimatedBoolean,SVGAnimatedEnumeration,SVGAnimatedInteger,SVGAnimatedLength,SVGAnimatedLengthList,SVGAnimatedNumber,SVGAnimatedNumberList,SVGAnimatedPreserveAspectRatio,SVGAnimatedRect,SVGAnimatedString,SVGAnimatedTransformList,' +
  55. 'SVGPathSegList,SVGPathSeg,SVGPathSegArcAbs,SVGPathSegArcRel,SVGPathSegClosePath,SVGPathSegCurvetoCubicAbs,SVGPathSegCurvetoCubicRel,SVGPathSegCurvetoCubicSmoothAbs,SVGPathSegCurvetoCubicSmoothRel,SVGPathSegCurvetoQuadraticAbs,SVGPathSegCurvetoQuadraticRel,SVGPathSegCurvetoQuadraticSmoothAbs,SVGPathSegCurvetoQuadraticSmoothRel,SVGPathSegLinetoAbs,SVGPathSegLinetoHorizontalAbs,SVGPathSegLinetoHorizontalRel,SVGPathSegLinetoRel,SVGPathSegLinetoVerticalAbs,SVGPathSegLinetoVerticalRel,SVGPathSegMovetoAbs,SVGPathSegMovetoRel,ElementTimeControl,TimeEvent,SVGAnimatedPathData,' +
  56. 'SVGAnimatedPoints,SVGColorProfileRule,SVGCSSRule,SVGExternalResourcesRequired,SVGFitToViewBox,SVGLangSpace,SVGLocatable,SVGRenderingIntent,SVGStylable,SVGTests,SVGTextContentElement,SVGTextPositioningElement,SVGTransformable,SVGUnitTypes,SVGURIReference,SVGViewSpec,SVGZoomAndPan');
  57. /**
  58. * Order of operation ENUMs.
  59. * https://developer.mozilla.org/en/OpenSCAD/Reference/Operators/Operator_Precedence
  60. */
  61. Blockly.OpenSCAD.ORDER_ATOMIC = 0; // 0 "" ...
  62. Blockly.OpenSCAD.ORDER_MEMBER = 1; // . []
  63. Blockly.OpenSCAD.ORDER_NEW = 1; // new
  64. Blockly.OpenSCAD.ORDER_FUNCTION_CALL = 2; // ()
  65. Blockly.OpenSCAD.ORDER_INCREMENT = 3; // ++
  66. Blockly.OpenSCAD.ORDER_DECREMENT = 3; // --
  67. Blockly.OpenSCAD.ORDER_LOGICAL_NOT = 4; // !
  68. Blockly.OpenSCAD.ORDER_BITWISE_NOT = 4; // ~
  69. Blockly.OpenSCAD.ORDER_UNARY_PLUS = 4; // +
  70. Blockly.OpenSCAD.ORDER_UNARY_NEGATION = 4; // -
  71. Blockly.OpenSCAD.ORDER_TYPEOF = 4; // typeof
  72. Blockly.OpenSCAD.ORDER_VOID = 4; // void
  73. Blockly.OpenSCAD.ORDER_DELETE = 4; // delete
  74. Blockly.OpenSCAD.ORDER_MULTIPLICATION = 5; // *
  75. Blockly.OpenSCAD.ORDER_DIVISION = 5; // /
  76. Blockly.OpenSCAD.ORDER_MODULUS = 5; // %
  77. Blockly.OpenSCAD.ORDER_ADDITION = 6; // +
  78. Blockly.OpenSCAD.ORDER_SUBTRACTION = 6; // -
  79. Blockly.OpenSCAD.ORDER_BITWISE_SHIFT = 7; // << >> >>>
  80. Blockly.OpenSCAD.ORDER_RELATIONAL = 8; // < <= > >=
  81. Blockly.OpenSCAD.ORDER_IN = 8; // in
  82. Blockly.OpenSCAD.ORDER_INSTANCEOF = 8; // instanceof
  83. Blockly.OpenSCAD.ORDER_EQUALITY = 9; // == != === !==
  84. Blockly.OpenSCAD.ORDER_BITWISE_AND = 10; // &
  85. Blockly.OpenSCAD.ORDER_BITWISE_XOR = 11; // ^
  86. Blockly.OpenSCAD.ORDER_BITWISE_OR = 12; // |
  87. Blockly.OpenSCAD.ORDER_LOGICAL_AND = 13; // &&
  88. Blockly.OpenSCAD.ORDER_LOGICAL_OR = 14; // ||
  89. Blockly.OpenSCAD.ORDER_CONDITIONAL = 15; // ?:
  90. Blockly.OpenSCAD.ORDER_ASSIGNMENT = 16; // = += -= *= /= %= <<= >>= ...
  91. Blockly.OpenSCAD.ORDER_COMMA = 17; // ,
  92. Blockly.OpenSCAD.ORDER_NONE = 99; // (...)
  93. /**
  94. * Arbitrary code to inject into locations that risk causing infinite loops.
  95. * Any instances of '%1' will be replaced by the block ID that failed.
  96. * E.g. ' checkTimeout(%1);\n'
  97. * @type ?string
  98. */
  99. Blockly.OpenSCAD.INFINITE_LOOP_TRAP = null;
  100. /**
  101. * Initialise the database of variable names.
  102. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  103. */
  104. Blockly.OpenSCAD.init = function(workspace) {
  105. // Create a dictionary of definitions to be printed before the code.
  106. Blockly.OpenSCAD.definitions_ = Object.create(null);
  107. // Create a dictionary mapping desired function names in definitions_
  108. // to actual function names (to avoid collisions with user functions).
  109. Blockly.OpenSCAD.functionNames_ = Object.create(null);
  110. if (!Blockly.OpenSCAD.variableDB_) {
  111. Blockly.OpenSCAD.variableDB_ =
  112. new Blockly.Names(Blockly.OpenSCAD.RESERVED_WORDS_);
  113. } else {
  114. Blockly.OpenSCAD.variableDB_.reset();
  115. }
  116. var defvars = [];
  117. var variables = Blockly.Variables.allVariables(workspace);
  118. // for (var x = 0; x < variables.length; x++) {
  119. // defvars[x] = 'var ' +
  120. // Blockly.OpenSCAD.variableDB_.getName(variables[x],
  121. // Blockly.Variables.NAME_TYPE) + ';';
  122. // }
  123. Blockly.OpenSCAD.definitions_['variables'] = defvars.join('\n');
  124. };
  125. /**
  126. * Prepend the generated code with the variable definitions.
  127. * @param {string} code Generated code.
  128. * @return {string} Completed code.
  129. */
  130. Blockly.OpenSCAD.finish = function(code) {
  131. // Convert the definitions dictionary into a list.
  132. var definitions = [];
  133. for (var name in Blockly.OpenSCAD.definitions_) {
  134. definitions.push(Blockly.OpenSCAD.definitions_[name]);
  135. }
  136. return '//!OpenSCAD\n\n' + definitions.join('\n') + '\n\n\n' + code;
  137. //return definitions.join('\n\n') + '\n\n\n' + code;
  138. };
  139. /**
  140. * Naked values are top-level blocks with outputs that aren't plugged into
  141. * anything. A trailing semicolon is needed to make this legal.
  142. * @param {string} line Line of generated code.
  143. * @return {string} Legal line of code.
  144. */
  145. Blockly.OpenSCAD.scrubNakedValue = function(line) {
  146. return line + ';\n';
  147. };
  148. /**
  149. * Encode a string as a properly escaped OpenSCAD string, complete with
  150. * quotes.
  151. * @param {string} string Text to encode.
  152. * @return {string} OpenSCAD string.
  153. * @private
  154. */
  155. Blockly.OpenSCAD.quote_ = function(string) {
  156. // TODO: This is a quick hack. Replace with goog.string.quote
  157. string = string.replace(/\\/g, '\\\\')
  158. .replace(/\n/g, '\\\n')
  159. .replace(/"/g, '\\\"');
  160. return '"' + string + '"';
  161. };
  162. /**
  163. * Common tasks for generating OpenSCAD from blocks.
  164. * Handles comments for the specified block and any connected value blocks.
  165. * Calls any statements following this block.
  166. * @param {!Blockly.Block} block The current block.
  167. * @param {string} code The OpenSCAD code created for this block.
  168. * @return {string} OpenSCAD code with comments and subsequent blocks added.
  169. * @this {Blockly.CodeGenerator}
  170. * @private
  171. */
  172. Blockly.OpenSCAD.scrub_ = function(block, code) {
  173. if (code === null) {
  174. // Block has handled code generation itself.
  175. return '';
  176. }
  177. var commentCode = '';
  178. // Only collect comments for blocks that aren't inline.
  179. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  180. // Collect comment for this block.
  181. var comment = block.getCommentText();
  182. if (comment) {
  183. commentCode += this.prefixLines(comment, '// ') + '\n';
  184. }
  185. // Collect comments for all value arguments.
  186. // Don't collect comments for nested statements.
  187. for (var x = 0; x < block.inputList.length; x++) {
  188. if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  189. var childBlock = block.inputList[x].connection.targetBlock();
  190. if (childBlock) {
  191. var comment = this.allNestedComments(childBlock);
  192. if (comment) {
  193. commentCode += this.prefixLines(comment, '// ');
  194. }
  195. }
  196. }
  197. }
  198. }
  199. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  200. var nextCode = this.blockToCode(nextBlock);
  201. return commentCode + code + nextCode;
  202. };