editor.js.html 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: editor.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: editor.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>/**
  20. * An object that manages the various editors, where users can edit their program. Also manages the
  21. * movement between editors.
  22. * There are currently four editors:
  23. * - Blocks: A Blockly instance
  24. * - Text: A CodeMirror instance
  25. * - Instructor: Features for changing the assignment and environment settings
  26. * - Upload: (Incomplete) A menu for uploading and running code from a desktop file.
  27. *
  28. * @constructor
  29. * @this {BlockPyEditor}
  30. * @param {Object} main - The main BlockPy instance
  31. * @param {HTMLElement} tag - The HTML object this is attached to.
  32. */
  33. function BlockPyEditor(main, tag) {
  34. this.main = main;
  35. this.tag = tag;
  36. // This tool is what actually converts text to blocks!
  37. this.converter = new PythonToBlocks();
  38. // HTML DOM accessors
  39. this.blockTag = tag.find('.blockpy-blocks');
  40. this.blocklyDiv = this.blockTag.find('.blockly-div');
  41. this.textTag = tag.find('.blockpy-text');
  42. this.uploadTag = tag.find('.blockpy-upload');
  43. this.instructorTag = tag.find('.blockpy-instructor');
  44. this.textSidebarTag = this.textTag.find(".blockpy-text-sidebar");
  45. // Blockly and CodeMirror instances
  46. this.blockly = null;
  47. this.codeMirror = null;
  48. // The updateStack keeps track of whether an update is percolating, to prevent duplicate update events.
  49. this.silenceBlock = false;
  50. this.silenceBlockTimer = null;
  51. this.silenceText = false;
  52. this.silenceModel = 0;
  53. this.blocksFailed = false;
  54. this.blocksFailedTimeout = null;
  55. // Hack to prevent chrome errors. Forces audio to load on demand.
  56. // See: https://github.com/google/blockly/issues/299
  57. Blockly.WorkspaceSvg.prototype.preloadAudio_ = function() {};
  58. // Keep track of the toolbox width
  59. this.blocklyToolboxWidth = 0;
  60. // Initialize subcomponents
  61. this.initText();
  62. this.initBlockly();
  63. this.initInstructor();
  64. var editor = this;
  65. // Handle mode switching
  66. this.main.model.settings.editor.subscribe(function() {editor.setMode()});
  67. // Handle level switching
  68. this.main.model.settings.level.subscribe(function() {editor.setLevel()});
  69. // Handle filename switching
  70. this.main.model.settings.filename.subscribe(function (name) {
  71. if (name == 'give_feedback') {
  72. editor.setMode('Text');
  73. }
  74. });
  75. // Have to force a manual block update
  76. //this.updateText();
  77. this.updateBlocksFromModel();
  78. this.updateTextFromModel();
  79. }
  80. /**
  81. * Initializes the Blockly instance (handles all the blocks). This includes
  82. * attaching a number of ChangeListeners that can keep the internal code
  83. * representation updated and enforce type checking.
  84. */
  85. BlockPyEditor.prototype.initBlockly = function() {
  86. this.blockly = Blockly.inject(this.blocklyDiv[0],
  87. { path: this.main.model.constants.blocklyPath,
  88. scrollbars: this.main.model.constants.blocklyScrollbars,
  89. readOnly: this.main.model.settings.read_only(),
  90. zoom: {enabled: false},
  91. toolbox: this.updateToolbox(false)});
  92. // Register model changer
  93. var editor = this;
  94. this.blockly.addChangeListener(function(evt) {
  95. //editor.main.components.feedback.clearEditorErrors();
  96. editor.blockly.highlightBlock(null);
  97. editor.updateBlocks();
  98. //editor.updateBlocks();
  99. });
  100. this.main.model.program.subscribe(function() {editor.updateBlocksFromModel()});
  101. this.main.model.settings.filename.subscribe(function() {
  102. /*if (editor.main.model.settings.editor() == "Blocks") {
  103. editor.updateBlocksFromModel()
  104. }*/
  105. });
  106. this.main.model.assignment.modules.subscribe(function() {editor.updateToolbox(true)});
  107. // Force the proper window size
  108. this.blockly.resize();
  109. // Keep the toolbox width set
  110. this.blocklyToolboxWidth = this.blockly.toolbox_.width;
  111. Blockly.captureDialog_ = this.copyImage.bind(this);
  112. // Enable static type checking!
  113. this.blockly.addChangeListener(function() {
  114. if (!editor.main.model.settings.disable_variable_types()) {
  115. var variables = editor.main.components.engine.analyzeVariables()
  116. editor.blockly.getAllBlocks().filter(function(r) {return r.type == 'variables_get'}).forEach(function(block) {
  117. var name = block.inputList[0].fieldRow[0].value_;
  118. if (name in variables) {
  119. var type = variables[name];
  120. if (type.type == "Num") {
  121. block.setOutput(true, "Number");
  122. } else if (type.type == "List") {
  123. block.setOutput(true, "Array");
  124. } else if (type.type == "Str") {
  125. block.setOutput(true, "String");
  126. } else {
  127. block.setOutput(true, null);
  128. }
  129. }
  130. })
  131. }
  132. });
  133. };
  134. /**
  135. * Initializes the CodeMirror instance. This handles text editing (with syntax highlighting)
  136. * and also attaches a listener for change events to update the internal code represntation.
  137. */
  138. BlockPyEditor.prototype.initText = function() {
  139. var codeMirrorDiv = this.textTag.find('.codemirror-div')[0];
  140. this.codeMirror = CodeMirror.fromTextArea(codeMirrorDiv, {
  141. mode: { name: "python",
  142. version: 3,
  143. singleLineStringErrors: false
  144. },
  145. readOnly: this.main.model.settings.read_only(),
  146. lineNumbers: true,
  147. firstLineNumber: 1,
  148. indentUnit: 4,
  149. tabSize: 4,
  150. indentWithTabs: false,
  151. matchBrackets: true,
  152. extraKeys: {"Tab": "indentMore",
  153. "Shift-Tab": "indentLess"},
  154. });
  155. // Register model changer
  156. var editor = this;
  157. this.codeMirror.on("change", function() {
  158. //editor.main.components.feedback.clearEditorErrors();
  159. editor.updateText()
  160. });
  161. this.main.model.program.subscribe(function() {editor.updateTextFromModel()});
  162. // Ensure that it fills the editor area
  163. this.codeMirror.setSize(null, "100%");
  164. // Was toying with buttons for injecting code. These are deprecated now.
  165. this.tag.find('.blockpy-text-insert-if').click(function() {
  166. var line_number = blockpy.components.editor.codeMirror.getCursor().line;
  167. var line = blockpy.components.editor.codeMirror.getLine(line_number);
  168. var whitespace = line.match(/^(\s*)/)[1];
  169. editor.codeMirror.replaceSelection("if ___:\n "+whitespace+"pass");
  170. });
  171. this.tag.find('.blockpy-text-insert-if-else').click(function() {
  172. var line_number = blockpy.components.editor.codeMirror.getCursor().line;
  173. var line = blockpy.components.editor.codeMirror.getLine(line_number);
  174. var whitespace = line.match(/^(\s*)/)[1];
  175. editor.codeMirror.replaceSelection("if ___:\n "+whitespace+"pass\n"+whitespace+"else:\n "+whitespace+"pass");
  176. });
  177. };
  178. /**
  179. * Initializes the Instructor tab, which has a number of buttons and menus for
  180. * manipulating assignments and the environment. One important job is to register the
  181. * SummerNote instance used for editing the Introduction of the assignment.
  182. */
  183. BlockPyEditor.prototype.initInstructor = function() {
  184. var introductionEditor = this.instructorTag.find('.blockpy-presentation-body-editor');
  185. var model = this.main.model;
  186. introductionEditor.summernote({
  187. codemirror: { // codemirror options
  188. theme: 'monokai'
  189. },
  190. onChange: model.assignment.introduction,
  191. toolbar: [
  192. ['style', ['bold', 'italic', 'underline', 'clear']],
  193. ['font', ['fontname', 'fontsize']],
  194. ['insert', ['link', 'table', 'ul', 'ol', 'image']],
  195. ['misc', ['codeview', 'help']]
  196. ]
  197. });
  198. introductionEditor.code(model.assignment.introduction());
  199. this.availableModules = this.instructorTag.find('.blockpy-available-modules');
  200. this.availableModules.multiSelect({ selectableOptgroup: true });
  201. }
  202. /**
  203. * Makes the module available in the availableModules multi-select menu by adding
  204. * it to the list.
  205. *
  206. * @param {String} name - The name of the module (human-friendly version, as opposed to the slug) to be added.
  207. */
  208. BlockPyEditor.prototype.addAvailableModule = function(name) {
  209. this.availableModules.multiSelect('addOption', {
  210. 'value': name, 'text': name
  211. });
  212. this.availableModules.multiSelect('select', name);
  213. };
  214. /**
  215. * Hides the Text tab, which involves shrinking it and hiding its CodeMirror too.
  216. */
  217. BlockPyEditor.prototype.hideSplitMenu = function() {
  218. this.hideTextMenu();
  219. this.hideBlockMenu();
  220. }
  221. /**
  222. * Shows the Text tab, which requires restoring its height, showing AND refreshing
  223. * the CodeMirror instance.
  224. */
  225. BlockPyEditor.prototype.showSplitMenu = function() {
  226. this.showBlockMenu();
  227. this.showTextMenu();
  228. this.textTag.css('width', '40%');
  229. this.blockTag.css('width', '60%');
  230. this.textSidebarTag.css('width', '0px');
  231. this.textTag.addClass('col-md-6');
  232. this.blockTag.addClass('col-md-6');
  233. Blockly.svgResize(this.blockly);
  234. }
  235. /**
  236. * Hides the Text tab, which involves shrinking it and hiding its CodeMirror too.
  237. */
  238. BlockPyEditor.prototype.hideTextMenu = function() {
  239. this.textTag.css('height', '0%');
  240. $(this.codeMirror.getWrapperElement()).hide();
  241. this.textSidebarTag.hide();
  242. this.textTag.hide();
  243. }
  244. /**
  245. * Shows the Text tab, which requires restoring its height, showing AND refreshing
  246. * the CodeMirror instance.
  247. */
  248. BlockPyEditor.prototype.showTextMenu = function() {
  249. this.textTag.show();
  250. // Adjust height
  251. this.textTag.css('height', '450px');
  252. this.textTag.css('width', '100%');
  253. // Show CodeMirror
  254. $(this.codeMirror.getWrapperElement()).show();
  255. // CodeMirror doesn't know its changed size
  256. this.codeMirror.refresh();
  257. // Resize sidebar
  258. var codemirrorGutterWidth = $('.CodeMirror-gutters').width();
  259. var sideBarWidth = this.blocklyToolboxWidth-codemirrorGutterWidth-2;
  260. this.textSidebarTag.css('width', sideBarWidth+'px');
  261. this.textSidebarTag.show();
  262. this.textTag.removeClass('col-md-6');
  263. }
  264. /**
  265. * Hides the Block tab, which involves shrinking it and hiding the Blockly instance.
  266. */
  267. BlockPyEditor.prototype.hideBlockMenu = function() {
  268. this.blocklyToolboxWidth = this.blockly.toolbox_.width;
  269. this.blockTag.css('height', '0%');
  270. this.blocklyDiv.css("width", "0");
  271. this.blockly.setVisible(false);
  272. }
  273. /**
  274. * Shows the Block tab, which involves restoring its height and showing the Blockly instance.
  275. */
  276. BlockPyEditor.prototype.showBlockMenu = function() {
  277. this.blockTag.css('height', '100%');
  278. this.blockTag.css('width', '100%');
  279. this.blocklyDiv.css("width", "100%");
  280. this.blockly.resize();
  281. this.blockly.setVisible(true);
  282. this.blockTag.removeClass('col-md-6');
  283. Blockly.svgResize(this.blockly);
  284. }
  285. /**
  286. * Hides the Upload tab, which shrinking it.
  287. */
  288. BlockPyEditor.prototype.hideUploadMenu = function() {
  289. this.uploadTag.hide();
  290. this.uploadTag.css('height', '0%');
  291. }
  292. /**
  293. * Shows the Upload tab, which involves restoring its height.
  294. */
  295. BlockPyEditor.prototype.showUploadMenu = function() {
  296. this.uploadTag.css('height', '100%');
  297. this.uploadTag.show();
  298. }
  299. /**
  300. * Hides the Instructor tab, which shrinking it.
  301. */
  302. BlockPyEditor.prototype.hideInstructorMenu = function() {
  303. this.instructorTag.hide();
  304. this.instructorTag.css('height', '0%');
  305. }
  306. /**
  307. * Shows the Instructor tab, which involves restoring its height.
  308. */
  309. BlockPyEditor.prototype.showInstructorMenu = function() {
  310. this.instructorTag.css('height', '100%');
  311. this.instructorTag.show();
  312. }
  313. /**
  314. * Sets the current editor mode to Text, hiding the other menus.
  315. * Also forces the text side to update.
  316. */
  317. BlockPyEditor.prototype.setModeToText = function() {
  318. this.hideBlockMenu();
  319. this.hideUploadMenu();
  320. this.hideInstructorMenu();
  321. this.showTextMenu();
  322. // Update the text model from the blocks
  323. }
  324. /**
  325. * Sets the current editor mode to Blocks, hiding the other menus.
  326. * Also forces the block side to update.
  327. * There is a chance this could fail, if the text side is irredeemably
  328. * awful. So then the editor bounces back to the text side.
  329. */
  330. BlockPyEditor.prototype.setModeToBlocks = function() {
  331. this.hideTextMenu();
  332. this.hideUploadMenu();
  333. this.hideInstructorMenu();
  334. this.showBlockMenu();
  335. if (this.blocksFailed !== false) {
  336. this.showConversionError();
  337. var main = this.main;
  338. main.model.settings.editor("Text");
  339. setTimeout(function() {
  340. main.components.toolbar.tags.mode_set_text.click();
  341. }, 0);
  342. }
  343. // Update the blocks model from the text
  344. /*
  345. success = this.updateBlocksFromModel();
  346. if (!success) {
  347. var main = this.main;
  348. main.components.editor.updateTextFromModel();
  349. main.model.settings.editor("Text");
  350. setTimeout(function() {
  351. main.components.toolbar.tags.mode_set_text.click();
  352. }, 0);
  353. }*/
  354. }
  355. /**
  356. * Sets the current editor mode to Upload mode, hiding the other menus.
  357. */
  358. BlockPyEditor.prototype.setModeToUpload = function() {
  359. this.hideTextMenu();
  360. this.hideInstructorMenu();
  361. this.hideBlockMenu();
  362. this.showUploadMenu();
  363. //TODO: finish upload mode
  364. }
  365. /**
  366. * Sets the current editor mode to Split mode, hiding the other menus.
  367. */
  368. BlockPyEditor.prototype.setModeToSplit = function() {
  369. this.hideTextMenu();
  370. this.hideInstructorMenu();
  371. this.hideBlockMenu();
  372. this.hideUploadMenu();
  373. this.showSplitMenu();
  374. if (this.blocksFailed !== false) {
  375. this.showConversionError();
  376. }
  377. }
  378. /**
  379. * Sets the current editor mode to the Instructor mode, hiding the other menus.
  380. */
  381. BlockPyEditor.prototype.setModeToInstructor = function() {
  382. this.hideTextMenu();
  383. this.hideBlockMenu();
  384. this.hideUploadMenu();
  385. this.showInstructorMenu();
  386. //TODO: finish upload mode
  387. //this.main.reportError("editor", "Instructor mode has not been implemented");
  388. }
  389. BlockPyEditor.prototype.changeMode = function() {
  390. if (main.model.settings.editor() == "Blocks") {
  391. main.model.settings.editor("Text");
  392. } else {
  393. main.model.settings.editor("Blocks");
  394. }
  395. }
  396. /**
  397. * Dispatch method to set the mode to the given argument.
  398. * If the mode is invalid, an editor error is reported. If the
  399. *
  400. * @param {String} mode - The new mode to set to ("Blocks", "Text", "Upload", or "Instructor")
  401. */
  402. BlockPyEditor.prototype.setMode = function(mode) {
  403. // Either update the model, or go with the model's
  404. if (mode === undefined) {
  405. mode = this.main.model.settings.editor();
  406. } else {
  407. this.main.model.settings.editor(mode);
  408. }
  409. // Dispatch according to new mode
  410. if (mode == 'Blocks') {
  411. this.setModeToBlocks();
  412. } else if (mode == 'Text') {
  413. this.setModeToText();
  414. } else if (mode == 'Upload') {
  415. this.setModeToUpload();
  416. } else if (mode == 'Split') {
  417. this.setModeToSplit();
  418. } else if (mode == 'Instructor') {
  419. this.setModeToInstructor();
  420. } else {
  421. this.components.feedback.internalError(""+mode, "Invalid Mode", "The editor attempted to change to an invalid mode.")
  422. }
  423. }
  424. /**
  425. * Actually changes the value of the CodeMirror instance
  426. *
  427. * @param {String} code - The new code for the CodeMirror
  428. */
  429. BlockPyEditor.prototype.setText = function(code) {
  430. if (code == undefined || code.trim() == "") {
  431. this.codeMirror.setValue("\n");
  432. } else {
  433. this.codeMirror.setValue(code);
  434. }
  435. // Ensure that we maintain proper highlighting
  436. this.refreshHighlight();
  437. }
  438. BlockPyEditor.prototype.showConversionError = function() {
  439. var error = this.blocksFailed;
  440. this.main.components.feedback.editorError(error, "While attempting to convert the Python code into blocks, I found a syntax error. In other words, your Python code has a spelling or grammatical mistake. You should check to make sure that you have written all of your code correctly. To me, it looks like the problem is on line "+ error.args.v[2]+', where it says:&lt;br>&lt;code>'+error.args.v[3][2]+'&lt;/code>', error.args.v[2]);
  441. }
  442. BlockPyEditor.prototype.setBlocks = function(python_code) {
  443. var xml_code = "";
  444. if (python_code !== '' &amp;&amp; python_code !== undefined &amp;&amp; python_code.trim().charAt(0) !== '&lt;') {
  445. var result = this.converter.convertSource(python_code);
  446. xml_code = result.xml;
  447. window.clearTimeout(this.blocksFailedTimeout);
  448. if (result.error !== null) {
  449. this.blocksFailed = result.error;
  450. var editor = this;
  451. this.blocksFailedTimeout = window.setTimeout(function() {
  452. if (editor.main.model.settings.editor() != 'Text') {
  453. editor.showConversionError();
  454. }
  455. }, 500)
  456. } else {
  457. this.blocksFailed = false;
  458. this.main.components.feedback.clearEditorErrors();
  459. }
  460. }
  461. var error_code = this.converter.convertSourceToCodeBlock(python_code);
  462. var errorXml = Blockly.Xml.textToDom(error_code);
  463. if (python_code == '' || python_code == undefined || python_code.trim() == '') {
  464. this.blockly.clear();
  465. } else if (xml_code !== '' &amp;&amp; xml_code !== undefined) {
  466. var blocklyXml = Blockly.Xml.textToDom(xml_code);
  467. try {
  468. this.setBlocksFromXml(blocklyXml);
  469. } catch (e) {
  470. console.error(e);
  471. this.setBlocksFromXml(errorXml);
  472. }
  473. } else {
  474. this.setBlocksFromXml(errorXml);
  475. }
  476. Blockly.Events.disable();
  477. // Parsons shuffling
  478. if (this.main.model.assignment.parsons()) {
  479. this.blockly.shuffle();
  480. } else {
  481. this.blockly.align();
  482. }
  483. Blockly.Events.enable();
  484. if (this.previousLine !== null) {
  485. this.refreshBlockHighlight(this.previousLine);
  486. }
  487. }
  488. BlockPyEditor.prototype.clearDeadBlocks = function() {
  489. var all_blocks = this.blockly.getAllBlocks();
  490. all_blocks.forEach(function(elem) {
  491. if (!Blockly.Python[elem.type]) {
  492. elem.dispose(true);
  493. }
  494. });
  495. }
  496. /**
  497. * Attempts to update the model for the current code file from the
  498. * block workspace. Might be prevented if an update event was already
  499. * percolating.
  500. */
  501. BlockPyEditor.prototype.updateBlocks = function() {
  502. if (! this.silenceBlock) {
  503. try {
  504. var newCode = Blockly.Python.workspaceToCode(this.blockly);
  505. } catch (e) {
  506. this.clearDeadBlocks();
  507. this.main.components.feedback.editorError("Unknown Block", "It looks like you attempted to paste or load some blocks that were not known. Typically, this is because you failed to load in the dataset before trying to paste in a data block. If there are any black blocks on the canvas, delete them before continuing.", "Unknown Block");
  508. }
  509. // Update Model
  510. this.silenceModel = 2;
  511. var changed = this.main.setCode(newCode);
  512. if (!changed) {
  513. this.silenceModel = 0;
  514. } else {
  515. // Update Text
  516. this.silenceText = true;
  517. this.setText(newCode);
  518. }
  519. }
  520. }
  521. /**
  522. * Attempts to update the model for the current code file from the
  523. * text editor. Might be prevented if an update event was already
  524. * percolating. Also unhighlights any lines.
  525. */
  526. var timerGuard = null;
  527. BlockPyEditor.prototype.updateText = function() {
  528. if (! this.silenceText) {
  529. var newCode = this.codeMirror.getValue();
  530. // Update Model
  531. this.silenceModel = 2;
  532. this.main.setCode(newCode);
  533. // Update Blocks
  534. this.silenceBlock = true;
  535. this.setBlocks(newCode);
  536. this.unhighlightLines();
  537. this.resetBlockSilence();
  538. }
  539. this.silenceText = false;
  540. }
  541. /**
  542. * Resets the silenceBlock after a short delay
  543. */
  544. BlockPyEditor.prototype.resetBlockSilence = function() {
  545. var editor = this;
  546. if (editor.silenceBlockTimer != null) {
  547. clearTimeout(editor.silenceBlockTimer);
  548. }
  549. this.silenceBlockTimer = window.setTimeout(function() {
  550. editor.silenceBlock = false;
  551. editor.silenceBlockTimer = null;
  552. }, 40);
  553. };
  554. /**
  555. * Updates the text editor from the current code file in the
  556. * model. Might be prevented if an update event was already
  557. * percolating.
  558. */
  559. BlockPyEditor.prototype.updateTextFromModel = function() {
  560. if (this.silenceModel == 0) {
  561. var code = this.main.model.program();
  562. this.silenceText = true;
  563. this.setText(code);
  564. } else {
  565. this.silenceModel -= 1;
  566. }
  567. }
  568. /**
  569. * Updates the block editor from the current code file in the
  570. * model. Might be prevented if an update event was already
  571. * percolating. This can also report an error if one occurs.
  572. *
  573. * @returns {Boolean} Returns true upon success.
  574. */
  575. BlockPyEditor.prototype.updateBlocksFromModel = function() {
  576. if (this.silenceModel == 0) {
  577. var code = this.main.model.program().trim();
  578. this.silenceBlock = true;
  579. this.setBlocks(code);
  580. this.resetBlockSilence();
  581. } else {
  582. this.silenceModel -= 1;
  583. }
  584. }
  585. /**
  586. * Helper function for retrieving the current Blockly workspace as
  587. * an XML DOM object.
  588. *
  589. * @returns {XMLDom} The blocks in the current workspace.
  590. */
  591. BlockPyEditor.prototype.getBlocksFromXml = function() {
  592. return Blockly.Xml.workspaceToDom(this.blockly);
  593. }
  594. /**
  595. * Helper function for setting the current Blockly workspace to
  596. * whatever XML DOM is given. This clears out any existing blocks.
  597. */
  598. BlockPyEditor.prototype.setBlocksFromXml = function(xml) {
  599. //this.blockly.clear();
  600. Blockly.Xml.domToWorkspaceDestructive(xml, this.blockly);
  601. //console.log(this.blockly.getAllBlocks());
  602. }
  603. /**
  604. * @property {Number} previousLine - Keeps track of the previously highlighted line.
  605. */
  606. BlockPyEditor.prototype.previousLine = null;
  607. /**
  608. * Assuming that a line has been highlighted previously, this will set the
  609. * line to be highlighted again. Used when we need to restore a highlight.
  610. */
  611. BlockPyEditor.prototype.refreshHighlight = function() {
  612. if (this.previousLine !== null) {
  613. this.codeMirror.addLineClass(this.previousLine, 'text', 'editor-error-line');
  614. }
  615. // TODO: Shouldn't this refresh the highlight in the block side too?
  616. }
  617. /**
  618. * Highlights a line of code in the CodeMirror instance. This applies the "active" style
  619. * which is meant to bring attention to a line, but not suggest it is wrong.
  620. *
  621. * @param {Number} line - The line of code to highlight. I think this is zero indexed?
  622. */
  623. BlockPyEditor.prototype.highlightLine = function(line) {
  624. if (this.previousLine !== null) {
  625. this.codeMirror.removeLineClass(this.previousLine, 'text', 'editor-active-line');
  626. this.codeMirror.removeLineClass(this.previousLine, 'text', 'editor-error-line');
  627. }
  628. this.codeMirror.addLineClass(line, 'text', 'editor-active-line');
  629. this.previousLine = line;
  630. }
  631. /**
  632. * Highlights a line of code in the CodeMirror instance. This applies the "error" style
  633. * which is meant to suggest that a line is wrong.
  634. *
  635. * @param {Number} line - The line of code to highlight. I think this is zero indexed?
  636. */
  637. BlockPyEditor.prototype.highlightError = function(line) {
  638. if (this.previousLine !== null) {
  639. this.codeMirror.removeLineClass(this.previousLine, 'text', 'editor-active-line');
  640. this.codeMirror.removeLineClass(this.previousLine, 'text', 'editor-error-line');
  641. }
  642. this.codeMirror.addLineClass(line, 'text', 'editor-error-line');
  643. this.refreshBlockHighlight(line);
  644. this.previousLine = line;
  645. }
  646. /**
  647. * Highlights a block in Blockly. Unfortunately, this is the same as selecting it.
  648. *
  649. * @param {Number} block - The ID of the block object to highlight.
  650. */
  651. BlockPyEditor.prototype.highlightBlock = function(block) {
  652. //this.blockly.highlightBlock(block);
  653. }
  654. /**
  655. * Used to restore a block's highlight when travelling from the code tab. This
  656. * uses a mapping between the blocks and text that is generated from the parser.
  657. * The parser has stored the relevant line numbers for each block in the XML of the
  658. * block. Very sophisticated, and sadly fairly fragile.
  659. * TODO: I believe there's some kind of off-by-one error here...
  660. *
  661. * @param {Number} line - The line of code to highlight. I think this is zero indexed?
  662. */
  663. BlockPyEditor.prototype.refreshBlockHighlight = function(line) {
  664. if (this.blocksFailed) {
  665. this.blocksFailed = false;
  666. return;
  667. }
  668. if (this.main.model.settings.editor() != "Blocks" &amp;&amp;
  669. this.main.model.settings.editor() != "Split") {
  670. return;
  671. }
  672. var all_blocks = this.blockly.getAllBlocks();
  673. //console.log(all_blocks.map(function(e) { return e.lineNumber }));
  674. var blockMap = {};
  675. all_blocks.forEach(function(elem) {
  676. var lineNumber = parseInt(elem.lineNumber, 10);
  677. if (lineNumber in blockMap) {
  678. blockMap[lineNumber].push(elem);
  679. } else {
  680. blockMap[lineNumber] = [elem];
  681. }
  682. });
  683. if (1+line in blockMap) {
  684. var hblocks = blockMap[1+line];
  685. var blockly = this.blockly;
  686. hblocks.forEach(function(elem) {
  687. //elem.addSelect();
  688. blockly.highlightBlock(elem.id, true);
  689. });
  690. /*if (hblocks.length > 0) {
  691. this.blockly.highlightBlock(hblocks[0].id, true);
  692. }*/
  693. }
  694. }
  695. /**
  696. * Removes the outline around a block. Currently unused.
  697. */
  698. BlockPyEditor.prototype.unhighlightBlock = function() {
  699. // TODO:
  700. }
  701. /**
  702. * Removes any highlight in the text code editor.
  703. *
  704. */
  705. BlockPyEditor.prototype.unhighlightLines = function() {
  706. if (this.previousLine !== null) {
  707. this.codeMirror.removeLineClass(this.previousLine, 'text', 'editor-active-line');
  708. this.codeMirror.removeLineClass(this.previousLine, 'text', 'editor-error-line');
  709. }
  710. this.previousLine = null;
  711. }
  712. /**
  713. * DEPRECATED, thankfully
  714. * Builds up an array indicating the relevant block ID for a given step.
  715. * Operates on the current this.blockly instance
  716. * It works by injecting __HIGHLIGHT__(id); at the start of every line of code
  717. * and then extracting that with regular expressions. This makes it vulnerable
  718. * if someone decides to use __HIGHLIGHT__ in their code. I'm betting on that
  719. * never being a problem, though. Still, this was a miserable way of accomplishing
  720. * the desired behavior.
  721. */
  722. BlockPyEditor.prototype.getHighlightMap = function() {
  723. // Protect the current STATEMENT_PREFIX
  724. var backup = Blockly.Python.STATEMENT_PREFIX;
  725. Blockly.Python.STATEMENT_PREFIX = '__HIGHLIGHT__(%1);';
  726. Blockly.Python.addReservedWords('__HIGHLIGHT__');
  727. // Get the source code, injected with __HIGHLIGHT__(id)
  728. var highlightedCode = Blockly.Python.workspaceToCode(this.blockly);
  729. Blockly.Python.STATEMENT_PREFIX = backup;
  730. // Build up the array by processing the highlighted code line-by-line
  731. var highlightMap = [];
  732. var lines = highlightedCode.split("\n");
  733. for (var i = 0; i &lt; lines.length; i++) {
  734. // Get the block ID from the line
  735. var id = lines[i].match(/\W*__HIGHLIGHT__\(\'(.+?)\'\)/);
  736. if (id !== null) {
  737. // Convert it into a base-10 number, because JavaScript.
  738. highlightMap[i] = parseInt(id[1], 10);
  739. }
  740. }
  741. return highlightMap;
  742. }
  743. /**
  744. * Updates the current file being edited in the editors.
  745. * This appears to be deprecated.
  746. *
  747. * @param {String} name - The name of the file being edited (e.g, "__main__", "starting_code")
  748. */
  749. BlockPyEditor.prototype.changeProgram = function(name) {
  750. this.silentChange_ = true;
  751. if (name == 'give_feedback') {
  752. this.setMode('Text');
  753. }
  754. this.model.settings.filename = name;
  755. this.editor.setPython(this.model.programs[name]);
  756. this.toolbar.elements.programs.find("[data-name="+name+"]").click();
  757. }
  758. /**
  759. * Eventually will be used to update "levels" of sophistication of the code interface.
  760. * Currently unimplemented and unused.
  761. */
  762. BlockPyEditor.prototype.setLevel = function() {
  763. var level = this.main.model.settings.level();
  764. }
  765. /**
  766. * Maps short category names in the toolbox to the full XML used to
  767. * represent that category as usual. This is kind of a clunky mechanism
  768. * for managing the different categories, and doesn't allow us to specify
  769. * individual blocks.
  770. */
  771. BlockPyEditor.CATEGORY_MAP = {
  772. 'Properties': '&lt;category name="Properties" custom="VARIABLE" colour="240">'+
  773. '&lt;/category>',
  774. 'Decisions': '&lt;category name="Decisions" colour="330">'+
  775. '&lt;block type="controls_if">&lt;/block>'+
  776. '&lt;block type="controls_if">&lt;mutation else="1">&lt;/mutation>&lt;/block>'+
  777. '&lt;block type="logic_compare">&lt;/block>'+
  778. '&lt;block type="logic_operation">&lt;/block>'+
  779. '&lt;block type="logic_negate">&lt;/block>'+
  780. '&lt;/category>',
  781. 'Iteration': '&lt;category name="Iteration" colour="300">'+
  782. '&lt;block type="controls_forEach">&lt;/block>'+
  783. '&lt;/category>',
  784. 'Functions': '&lt;category name="Functions" custom="PROCEDURE" colour="210">'+
  785. '&lt;/category>',
  786. 'Calculation': '&lt;category name="Calculation" colour="270">'+
  787. //'&lt;block type="raw_table">&lt;/block>'+
  788. '&lt;block type="math_arithmetic">&lt;/block>'+
  789. //'&lt;block type="type_check">&lt;/block>'+
  790. //'&lt;block type="raw_empty">&lt;/block>'+
  791. //'&lt;block type="math_single">&lt;/block>'+
  792. //'&lt;block type="math_number_property">&lt;/block>'+
  793. '&lt;block type="math_round">&lt;/block>'+
  794. //'&lt;block type="text_join">&lt;/block>'+
  795. '&lt;/category>',
  796. 'Python': '&lt;category name="Python" colour="180">'+
  797. '&lt;block type="raw_block">&lt;/block>'+
  798. '&lt;block type="raw_expression">&lt;/block>'+
  799. //'&lt;block type="function_call">&lt;/block>'+
  800. '&lt;/category>',
  801. 'Output': '&lt;category name="Output" colour="160">'+
  802. '&lt;block type="text_print">&lt;/block>'+
  803. //'&lt;block type="text_print_multiple">&lt;/block>'+
  804. '&lt;block type="plot_line">&lt;/block>'+
  805. '&lt;block type="plot_scatter">&lt;/block>'+
  806. '&lt;block type="plot_hist">&lt;/block>'+
  807. '&lt;block type="plot_show">&lt;/block>'+
  808. '&lt;block type="plot_title">&lt;/block>'+
  809. '&lt;block type="plot_xlabel">&lt;/block>'+
  810. '&lt;block type="plot_ylabel">&lt;/block>'+
  811. '&lt;/category>',
  812. 'Turtles': '&lt;category name="Turtles" colour="180">'+
  813. '&lt;block type="turtle_create">&lt;/block>'+
  814. '&lt;block type="turtle_forward">&lt;/block>'+
  815. '&lt;block type="turtle_backward">&lt;/block>'+
  816. '&lt;block type="turtle_left">&lt;/block>'+
  817. '&lt;block type="turtle_right">&lt;/block>'+
  818. '&lt;block type="turtle_color">&lt;/block>'+
  819. '&lt;/category>',
  820. 'Values': '&lt;category name="Values" colour="100">'+
  821. '&lt;block type="text">&lt;/block>'+
  822. '&lt;block type="math_number">&lt;/block>'+
  823. '&lt;block type="logic_boolean">&lt;/block>'+
  824. '&lt;/category>',
  825. 'Lists': '&lt;category name="Lists" colour="30">'+
  826. '&lt;block type="lists_create_with">'+
  827. '&lt;value name="ADD0">'+
  828. '&lt;block type="math_number">&lt;field name="NUM">0&lt;/field>&lt;/block>'+
  829. '&lt;/value>'+
  830. '&lt;value name="ADD1">'+
  831. '&lt;block type="math_number">&lt;field name="NUM">0&lt;/field>&lt;/block>'+
  832. '&lt;/value>'+
  833. '&lt;value name="ADD2">'+
  834. '&lt;block type="math_number">&lt;field name="NUM">0&lt;/field>&lt;/block>'+
  835. '&lt;/value>'+
  836. '&lt;/block>'+
  837. '&lt;block type="lists_create_with">&lt;/block>'+
  838. '&lt;block type="lists_create_empty">&lt;/block>'+
  839. '&lt;block type="lists_append">&lt;/block>'+
  840. /*'&lt;block type="lists_length">&lt;/block>'+*/
  841. /*'&lt;block type="lists_index">'+
  842. '&lt;value name="ITEM">'+
  843. '&lt;shadow type="math_number">'+
  844. '&lt;field name="NUM">0&lt;/field>'+
  845. '&lt;/shadow>'+
  846. '&lt;/value>'+
  847. '&lt;/block>'+*/
  848. '&lt;/category>',
  849. 'Dictionaries': '&lt;category name="Dictionaries" colour="0">'+
  850. '&lt;block type="dicts_create_with">&lt;/block>'+
  851. '&lt;block type="dict_get_literal">&lt;/block>'+
  852. //'&lt;block type="dict_keys">&lt;/block>'+
  853. '&lt;/category>',
  854. /*
  855. 'Data - Weather': '&lt;category name="Data - Weather" colour="70">'+
  856. '&lt;block type="weather_temperature">&lt;/block>'+
  857. '&lt;block type="weather_report">&lt;/block>'+
  858. '&lt;block type="weather_forecasts">&lt;/block>'+
  859. '&lt;block type="weather_report_forecasts">&lt;/block>'+
  860. '&lt;block type="weather_all_forecasts">&lt;/block>'+
  861. '&lt;block type="weather_highs_lows">&lt;/block>'+
  862. '&lt;/category>',
  863. 'Data - Stocks': '&lt;category name="Data - Stock" colour="65">'+
  864. '&lt;block type="stocks_current">&lt;/block>'+
  865. '&lt;block type="stocks_past">&lt;/block>'+
  866. '&lt;/category>',
  867. 'Data - Earthquakes': '&lt;category name="Data - Earthquakes" colour="60">'+
  868. '&lt;block type="earthquake_get">&lt;/block>'+
  869. '&lt;block type="earthquake_both">&lt;/block>'+
  870. '&lt;block type="earthquake_all">&lt;/block>'+
  871. '&lt;/category>',
  872. 'Data - Crime': '&lt;category name="Data - Crime" colour="55">'+
  873. '&lt;block type="crime_state">&lt;/block>'+
  874. '&lt;block type="crime_year">&lt;/block>'+
  875. '&lt;block type="crime_all">&lt;/block>'+
  876. '&lt;/category>',
  877. 'Data - Books': '&lt;category name="Data - Books" colour="50">'+
  878. '&lt;block type="books_get">&lt;/block>'+
  879. '&lt;/category>',*/
  880. 'Data - Parking': '&lt;category name="Data - Parking" colour="45">'+
  881. '&lt;block type="datetime_day">&lt;/block>'+
  882. '&lt;block type="datetime_time">&lt;/block>'+
  883. '&lt;block type="logic_compare">'+
  884. '&lt;field name="OP">EQ&lt;/field>'+
  885. '&lt;value name="A">'+
  886. '&lt;block type="datetime_time">'+
  887. '&lt;mutation isNow="1">&lt;/mutation>'+
  888. '&lt;field name="HOUR">1&lt;/field>'+
  889. '&lt;field name="MINUTE">00&lt;/field>'+
  890. '&lt;field name="MERIDIAN">PM&lt;/field>'+
  891. '&lt;/block>'+
  892. '&lt;/value>'+
  893. '&lt;/block>'+
  894. '&lt;block type="logic_compare">'+
  895. '&lt;field name="OP">EQ&lt;/field>'+
  896. '&lt;value name="A">'+
  897. '&lt;block type="datetime_day">'+
  898. '&lt;field name="DAY">Monday&lt;/field>'+
  899. '&lt;/block>'+
  900. '&lt;/value>'+
  901. '&lt;/block>'+
  902. //'&lt;block type="datetime_check_day">&lt;/block>'+
  903. //'&lt;block type="datetime_check_time">&lt;/block>'+
  904. '&lt;/category>',
  905. 'Separator': '&lt;sep>&lt;/sep>'
  906. };
  907. /**
  908. * Creates an updated representation of the Toolboxes XML as currently specified in the
  909. * model, using whatever modules have been added or removed. This method can either set it
  910. * or just retrieve it for future use.
  911. *
  912. * @param {Boolean} only_set - Whether to return the XML string or to actually set the XML. False means that it will not update the toolbox!
  913. * @returns {String?} Possibly returns the XML of the toolbox as a string.
  914. */
  915. BlockPyEditor.prototype.updateToolbox = function(only_set) {
  916. var xml = '&lt;xml id="toolbox" style="display: none">';
  917. var modules = this.main.model.assignment.modules();
  918. var started_misc = false,
  919. started_values = false,
  920. started_data = false;
  921. for (var i = 0, length = modules.length; i &lt; length; i = i+1) {
  922. var module = modules[i];
  923. if (!started_misc &amp;&amp; ['Calculation', 'Output', 'Python'].indexOf(module) != -1) {
  924. started_misc = true;
  925. xml += BlockPyEditor.CATEGORY_MAP['Separator'];
  926. }
  927. if (!started_values &amp;&amp; ['Values', 'Lists', 'Dictionaries'].indexOf(module) != -1) {
  928. started_values = true;
  929. xml += BlockPyEditor.CATEGORY_MAP['Separator'];
  930. }
  931. if (!started_data &amp;&amp; module.slice(0, 6) == 'Data -') {
  932. started_data = true;
  933. xml += BlockPyEditor.CATEGORY_MAP['Separator'];
  934. }
  935. if (typeof module == 'string') {
  936. xml += BlockPyEditor.CATEGORY_MAP[module];
  937. } else {
  938. var category = '&lt;category name="'+module.name+'" colour="'+module.color+'">';
  939. for (var j= 0; category_length = module.blocks.length; j = j+1) {
  940. var block = module.blocks[j];
  941. category += '&lt;block type="'+block+'">&lt;/block>';
  942. }
  943. category += '&lt;/category>';
  944. }
  945. //'&lt;sep>&lt;/sep>'+
  946. }
  947. xml += '&lt;/xml>';
  948. if (only_set) {
  949. this.blockly.updateToolbox(xml);
  950. this.blockly.resize();
  951. } else {
  952. return xml;
  953. }
  954. };
  955. BlockPyEditor.prototype.DOCTYPE = '&lt;?xml version="1.0" standalone="no"?>' + '&lt;' + '!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
  956. BlockPyEditor.prototype.cssData = null;
  957. BlockPyEditor.prototype.loadCss = function() {
  958. if (this.cssData == null) {
  959. var txt = '.blocklyDraggable {}\n';
  960. txt += Blockly.Css.CONTENT.join('\n');
  961. if (Blockly.FieldDate) {
  962. txt += Blockly.FieldDate.CSS.join('\n');
  963. }
  964. // Strip off any trailing slash (either Unix or Windows).
  965. this.cssData = txt.replace(/&lt;&lt;&lt;PATH>>>/g, Blockly.Css.mediaPath_);
  966. }
  967. }
  968. /**
  969. * Generates a PNG version of the current workspace. This PNG is stored in a Base-64 encoded
  970. * string as part of a data URL (e.g., "data:image/png;base64,...").
  971. * TODO: There seems to be some problems capturing blocks that don't start with
  972. * statement level blocks (e.g., expression blocks).
  973. *
  974. * @param {Function} callback - A function to be called with the results. This function should take two parameters, the URL (as a string) of the generated base64-encoded PNG and the IMG tag.
  975. */
  976. BlockPyEditor.prototype.getPngFromBlocks = function(callback) {
  977. this.loadCss();
  978. try {
  979. // Retreive the entire canvas, strip some unnecessary tags
  980. var blocks = this.blockly.svgBlockCanvas_.cloneNode(true);
  981. blocks.removeAttribute("width");
  982. blocks.removeAttribute("height");
  983. // Ensure that we have some content
  984. if (blocks.childNodes[0] !== undefined) {
  985. // Remove tags that offset
  986. blocks.removeAttribute("transform");
  987. blocks.childNodes[0].removeAttribute("transform");
  988. blocks.childNodes[0].childNodes[0].removeAttribute("transform");
  989. // Add in styles
  990. var linkElm = document.createElementNS("http://www.w3.org/1999/xhtml", "style");
  991. linkElm.textContent = this.cssData + '\n\n';
  992. blocks.insertBefore(linkElm, blocks.firstChild);
  993. // Get the bounding box
  994. var bbox = document.getElementsByClassName("blocklyBlockCanvas")[0].getBBox();
  995. // Create the XML representation of the SVG
  996. var xml = new XMLSerializer().serializeToString(blocks);
  997. xml = '&lt;svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="'+bbox.width+'" height="'+bbox.height+'" viewBox="0 0 '+bbox.width+' '+bbox.height+'">&lt;rect width="100%" height="100%" fill="white">&lt;/rect>'+xml+'&lt;/svg>';
  998. // create a file blob of our SVG.
  999. // Unfortunately, this crashes modern chrome for unknown reasons.
  1000. //var blob = new Blob([ this.DOCTYPE + xml], { type: 'image/svg+xml' });
  1001. //var url = window.URL.createObjectURL(blob);
  1002. // Old method: this failed on IE
  1003. var url = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(xml)));
  1004. // Create an IMG tag to hold the new element
  1005. var img = document.createElement("img");
  1006. img.style.display = 'block';
  1007. img.onload = function() {
  1008. var canvas = document.createElement('canvas');
  1009. canvas.width = bbox.width;
  1010. canvas.height = bbox.height;
  1011. var ctx = canvas.getContext('2d');
  1012. ctx.drawImage(img, 0, 0);
  1013. var canvasUrl;
  1014. try {
  1015. canvasUrl = canvas.toDataURL("image/png");
  1016. } catch (e) {
  1017. canvasUrl = url;
  1018. }
  1019. img.onload = null;
  1020. callback(canvasUrl, img);
  1021. }
  1022. img.onerror = function() {
  1023. callback("", img);
  1024. }
  1025. img.setAttribute('src', url);
  1026. } else {
  1027. callback("", document.createElement("img"))
  1028. }
  1029. } catch (e) {
  1030. callback("", document.createElement("img"));
  1031. console.error("PNG image creation not supported!", e);
  1032. }
  1033. }
  1034. /**
  1035. * Shows a dialog window with the current block workspace encoded as a
  1036. * downloadable PNG image.
  1037. */
  1038. BlockPyEditor.prototype.copyImage = function() {
  1039. var dialog = this.main.components.dialog;
  1040. this.getPngFromBlocks(function(canvasUrl, img) {
  1041. img.onload = function() {
  1042. var span = document.createElement('span');
  1043. span.textContent = "Right-click and copy the image below."
  1044. var newWindow = document.createElement('button');
  1045. var newWindowInner = document.createElement('span');
  1046. newWindow.className += "btn btn-default btn-xs";
  1047. newWindowInner.className += "glyphicon glyphicon-new-window";
  1048. newWindow.onclick = function() {
  1049. var output = img.src;
  1050. window.open(img.src);
  1051. }
  1052. newWindow.appendChild(newWindowInner);
  1053. var div = document.createElement('div');
  1054. div.appendChild(span);
  1055. div.appendChild(newWindow);
  1056. div.appendChild(img);
  1057. dialog.show("Blocks as Image", div);
  1058. };
  1059. img.src = canvasUrl;
  1060. });
  1061. }</code></pre>
  1062. </article>
  1063. </section>
  1064. </div>
  1065. <nav>
  1066. <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="BlockPy.html">BlockPy</a></li><li><a href="BlockPyCorgis.html">BlockPyCorgis</a></li><li><a href="BlockPyDialog.html">BlockPyDialog</a></li><li><a href="BlockPyEditor.html">BlockPyEditor</a></li><li><a href="BlockPyEngine.html">BlockPyEngine</a></li><li><a href="BlockPyEnglish.html">BlockPyEnglish</a></li><li><a href="BlockPyFeedback.html">BlockPyFeedback</a></li><li><a href="BlockPyHistory.html">BlockPyHistory</a></li><li><a href="BlockPyPresentation.html">BlockPyPresentation</a></li><li><a href="BlockPyPrinter.html">BlockPyPrinter</a></li><li><a href="BlockPyServer.html">BlockPyServer</a></li><li><a href="BlockPyToolbar.html">BlockPyToolbar</a></li><li><a href="LocalStorageWrapper.html">LocalStorageWrapper</a></li><li><a href="PythonToBlocks.html">PythonToBlocks</a></li></ul><h3>Global</h3><ul><li><a href="global.html#BlockPyInterface">BlockPyInterface</a></li><li><a href="global.html#cloneNode">cloneNode</a></li><li><a href="global.html#encodeHTML">encodeHTML</a></li><li><a href="global.html#expandArray">expandArray</a></li><li><a href="global.html#EXTENDED_ERROR_EXPLANATION">EXTENDED_ERROR_EXPLANATION</a></li><li><a href="global.html#indent">indent</a></li><li><a href="global.html#instructor_module">instructor_module</a></li><li><a href="global.html#prettyPrintDateTime">prettyPrintDateTime</a></li><li><a href="global.html#randomInteger">randomInteger</a></li><li><a href="global.html#set_button_loaded">set_button_loaded</a></li><li><a href="global.html#timerGuard">timerGuard</a></li></ul>
  1067. </nav>
  1068. <br class="clear">
  1069. <footer>
  1070. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on Sun Mar 26 2017 09:45:03 GMT-0400 (Eastern Daylight Time)
  1071. </footer>
  1072. <script> prettyPrint(); </script>
  1073. <script src="scripts/linenumber.js"> </script>
  1074. </body>
  1075. </html>