not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
6.2 KiB

  1. # Copyright (C) 2015 Sam Parkinson
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. import re
  16. import sys
  17. import json
  18. HELP = '''Usage:
  19. python pluginify.py (file)
  20. or
  21. python pluginify.py (file) > plugin.json
  22. Converts an RTP (readable TurtleBlocks plugin) file into a JSON file
  23. to load into Turtle Blocks JS. For more information, run
  24. `python pluginify.py syntax`
  25. '''
  26. SYNTAX = '''
  27. In an RST file, new blocks are not defined with braces (as is typical of
  28. Javascript); rather they start whenever you add //* *// and their scope is
  29. until the next block starts (or the end of file in the case that it is
  30. the last block).
  31. To add a comment, just type //* comment *// followed by your multi-
  32. line comment. pluginify ignores comments, i.e., they are not added in
  33. the JSON plugin.
  34. Example:
  35. //* comment *// Your single or multi line comment here...
  36. Global variables are defined in a section //* globals *//.
  37. Example:
  38. //* globals *//
  39. var calories = 0;
  40. var protein = 0;
  41. var carbohydrate = 0;
  42. var fiber = 0;
  43. var fat = 0;
  44. Define all the global variables under the section
  45. //* block-globals *//.
  46. These definitions will be added to all the code blocks in the created
  47. JSON output. Note that these "globals" included in each block but are
  48. local in context to each block.
  49. Example: You can define a common API Key to be used by all blocks.
  50. //* block-globals *//
  51. var mashapeKey = '(keycode)'; in globals.
  52. You can also declare global variables specific to argument blocks that
  53. get applied to a set of similar blocks, e.g., the variables under
  54. //* arg-globals *// will be added to all the arg blocks.
  55. Example:
  56. //* arg-globals *//
  57. var block = blocks.blockList[blk];
  58. var connections = block.connections;
  59. You can declare functions for parameter blocks to be evaluated when
  60. the block labels are updated with the //* parameter:(blockname) *//
  61. tag.
  62. Example:
  63. //* parameter:loudness *//
  64. if (mic == null) {errorMsg("The microphone is not available.");
  65. value = 0;
  66. } else {
  67. value = Math.round(mic.getLevel() * 1000);
  68. }
  69. To define a block you need to type: //* block:(blockname) *//
  70. Example:
  71. //* block:power *//
  72. var block = new ProtoBlock('power');
  73. block.palette = palettes.dict['maths'];
  74. blocks.protoBlockDict['power'] = block;
  75. block.twoArgMathBlock();
  76. block.defaults.push(10, 2);
  77. block.staticLabels.push('power', 'base', 'exp.');
  78. You should also define a setter for a parameter block (if appropriate).
  79. You can do this using the setter setion:
  80. //* setter:myValue *//
  81. myValue = value;
  82. updateDisplayOfMyValue();
  83. Graphical elements (icons, colors) are defined in the own sections:
  84. Palette icons are defined as //* palette-icon:(palette name) *//
  85. Example:
  86. //* palette-icon:food *//
  87. <svg ...> ... </svg>
  88. Similarly for block colors:
  89. Example:
  90. //* palette-fill:food *// #FFFFFF
  91. //* palette-stroke:food *// #A0A0A0
  92. //* palette-highlight:food *// #D5D5D5
  93. Plugins can specify code to be executed on load, on start, and on stop.
  94. Example:
  95. //* onload:foo *//
  96. your code here...
  97. NOTE: name of on load, on start, and on stop sections must match the
  98. name of one of the plugin blocks.
  99. '''
  100. def clear():
  101. global NAMES, JS_TYPES, IMAGES
  102. NAMES = {
  103. 'flow': 'FLOWPLUGINS',
  104. 'arg': 'ARGPLUGINS',
  105. 'block': 'BLOCKPLUGINS',
  106. 'parameter': 'PARAMETERPLUGINS',
  107. 'setter': 'SETTERPLUGINS',
  108. 'onload': 'ONLOAD',
  109. 'onstart': 'ONSTART',
  110. 'onstop': 'ONSTOP',
  111. 'palette-icon': 'PALETTEPLUGINS',
  112. 'palette-fill': 'PALETTEFILLCOLORS',
  113. 'palette-stroke': 'PALETTESTROKECOLORS',
  114. 'palette-highlight': 'PALETTEHIGHLIGHTCOLORS',
  115. 'palette-stroke-highlight': 'HIGHLIGHTSTROKECOLORS'}
  116. JS_TYPES = ('flow', 'arg', 'block', 'parameter', 'setter', 'onload', 'onstart', 'onstop')
  117. # 'blkName': 'imageData',
  118. IMAGES = []
  119. def pluginify(data):
  120. clear()
  121. sections_list = data.split('//*')
  122. sections_pairs = []
  123. specific_globals = {x: '' for x in JS_TYPES}
  124. globals_ = None
  125. for section in sections_list:
  126. match = re.match('(.*)\*\/\/([^\0]*)', section.strip())
  127. if match:
  128. if match.group(1).strip() == 'globals':
  129. globals_ = match.group(2).strip()
  130. elif match.group(1).strip().endswith('-globals'):
  131. type_, _ = match.group(1).strip().split('-')
  132. specific_globals[type_] = specific_globals[type_] + \
  133. match.group(2).strip()
  134. elif match.group(1).strip() == 'comment':
  135. continue
  136. else:
  137. sections_pairs.append((match.group(1).strip(),
  138. match.group(2).strip()))
  139. outp = {}
  140. if globals_ is not None:
  141. outp['GLOBALS'] = globals_.replace('\n', '').replace('var ', '')
  142. for key, value in sections_pairs:
  143. if len(key.split(':')) != 2:
  144. raise ValueError('Section names should have 1 colon (type:name)')
  145. type_, name = key.split(':')
  146. if type_ in JS_TYPES:
  147. value = specific_globals[type_] + value
  148. value = value.replace('\n', '')
  149. if type_ in NAMES:
  150. type_ = NAMES[type_]
  151. if type_ not in outp:
  152. outp[type_] = []
  153. outp[type_].append([name,value])
  154. if type_ == 'image':
  155. # TODO: Detect if its png
  156. IMAGES.append([name, 'data:image/svg+xml;utf8,' + value])
  157. if IMAGES:
  158. outp['IMAGES'] = IMAGES
  159. return json.dumps(outp, indent=4)
  160. if __name__ == '__main__':
  161. if len(sys.argv) != 2:
  162. print HELP
  163. elif sys.argv[1] in ('help', '-h', '--help'):
  164. print HELP
  165. elif sys.argv[1] == 'syntax':
  166. print SYNTAX
  167. else:
  168. with open(sys.argv[1]) as f:
  169. data = f.read()
  170. print pluginify(data)