functions.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. import { Types } from './types';
  2. import * as Models from './ivprog_elements';
  3. import { LocalizedStrings } from './../services/localizedStringsService';
  4. import * as GlobalsManagement from './globals';
  5. import * as VariablesManagement from './variables';
  6. import * as CommandsManagement from './commands';
  7. import * as CodeManagement from './code_generator';
  8. import * as VariableValueMenu from './commands/variable_value_menu';
  9. import { DOMConsole } from './../io/domConsole';
  10. import { IVProgProcessor } from './../processor/ivprogProcessor';
  11. import WatchJS from 'melanke-watchjs';
  12. import { SemanticAnalyser } from '../processor/semantic/semanticAnalyser';
  13. import { IVProgAssessment } from '../assessment/ivprogAssessment';
  14. import * as AlgorithmManagement from './algorithm';
  15. import * as Utils from './utils';
  16. import { registerUserEvent, ActionTypes } from "./../services/userLog";
  17. import VersionInfo from './../../.ima_version.json';
  18. import * as TextEditor from "./text_editor";
  19. import { isValidIdentifier } from "./../util/utils";
  20. import { Modes } from '../processor/modes';
  21. var counter_new_functions = 0;
  22. var counter_new_parameters = 0;
  23. var ivprog_version = VersionInfo.version;
  24. const globalChangeListeners = [];
  25. const functionsChangeListeners = [];
  26. let proc = null;
  27. let domConsole = null;
  28. let _testCases = [];
  29. let isRunning = false;
  30. window.studentGrade = null;
  31. window.LocalizedStrings = LocalizedStrings;
  32. const program = new Models.Program();
  33. window.system_functions = [];
  34. // Adding math functions:
  35. window.system_functions.push(new Models.SystemFunction('$sin', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  36. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  37. window.system_functions.push(new Models.SystemFunction('$cos', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  38. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  39. window.system_functions.push(new Models.SystemFunction('$tan', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  40. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  41. window.system_functions.push(new Models.SystemFunction('$sqrt', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  42. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  43. window.system_functions.push(new Models.SystemFunction('$pow', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  44. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  45. window.system_functions.push(new Models.SystemFunction('$log', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  46. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  47. window.system_functions.push(new Models.SystemFunction('$abs', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  48. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  49. window.system_functions.push(new Models.SystemFunction('$negate', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  50. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  51. window.system_functions.push(new Models.SystemFunction('$invert', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  52. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  53. window.system_functions.push(new Models.SystemFunction('$max', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  54. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  55. window.system_functions.push(new Models.SystemFunction('$min', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  56. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  57. window.system_functions.push(new Models.SystemFunction('$rand', Types.REAL, 0, [],
  58. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  59. // Adding text functions:
  60. window.system_functions.push(new Models.SystemFunction('$substring', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true),
  61. new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true),new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  62. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  63. window.system_functions.push(new Models.SystemFunction('$length', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  64. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  65. window.system_functions.push(new Models.SystemFunction('$uppercase', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  66. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  67. window.system_functions.push(new Models.SystemFunction('$lowercase', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  68. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  69. window.system_functions.push(new Models.SystemFunction('$charAt', Types.CHAR, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  70. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  71. // Adding arrangement functions:
  72. window.system_functions.push(new Models.SystemFunction('$numElements', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 1)],
  73. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  74. window.system_functions.push(new Models.SystemFunction('$matrixLines', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 2)],
  75. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  76. window.system_functions.push(new Models.SystemFunction('$matrixColumns', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 2)],
  77. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  78. // Adding conversion functions:
  79. window.system_functions.push(new Models.SystemFunction('$isReal', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  80. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  81. window.system_functions.push(new Models.SystemFunction('$isInt', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  82. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  83. window.system_functions.push(new Models.SystemFunction('$isBool', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  84. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  85. window.system_functions.push(new Models.SystemFunction('$castReal', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  86. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  87. window.system_functions.push(new Models.SystemFunction('$castInt', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  88. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  89. window.system_functions.push(new Models.SystemFunction('$castBool', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  90. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  91. window.system_functions.push(new Models.SystemFunction('$castString', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  92. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  93. window.system_functions.push(new Models.SystemFunction('$castChar', Types.CHAR, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  94. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  95. console.log(' ___ ___ ________ \n / / / / / ____/ \n / / / / / / \n / / / / ______ ___ / /__ \n / / / / / \\ / / / ___/ \n / /______ / / / /\\ \\/ / / / \n / / / / / / \\ / / /____ \n/__________/ /___/ /___/ \\___/ /________/ \n\n Laboratório de Informática na Educação\n http://line.ime.usp.br');
  96. const mainFunction = new Models.Function(LocalizedStrings.getUI("start"), Types.VOID, 0, [], true, false);
  97. mainFunction.function_comment = new Models.Comment(LocalizedStrings.getUI('text_comment_main'));
  98. program.addFunction(mainFunction);
  99. window.program_obj = program;
  100. window.generator = CodeManagement.generate;
  101. window.runCodeAssessment = runCodeAssessment;
  102. window.renderAlgorithm = AlgorithmManagement.renderAlgorithm;
  103. window.insertContext = false;
  104. window.watchW = WatchJS;
  105. WatchJS.watch(window.program_obj.globals, function(){
  106. if (window.insertContext) {
  107. setTimeout(function() {
  108. AlgorithmManagement.renderAlgorithm();
  109. globalChangeListeners.forEach(x => x());
  110. }, 300);
  111. window.insertContext = false;
  112. } else {
  113. AlgorithmManagement.renderAlgorithm();
  114. globalChangeListeners.forEach(x => x());
  115. }
  116. }, 1);
  117. WatchJS.watch(window.program_obj.functions, function(){
  118. if (window.insertContext) {
  119. setTimeout(function(){
  120. AlgorithmManagement.renderAlgorithm();
  121. functionsChangeListeners.forEach( x => x());
  122. }, 300);
  123. window.insertContext = false;
  124. } else {
  125. AlgorithmManagement.renderAlgorithm();
  126. functionsChangeListeners.forEach( x => x());
  127. }
  128. }, 1);
  129. function addFunctionHandler () {
  130. if (window.program_obj.functions) {
  131. var in_use = false;
  132. do {
  133. in_use = false;
  134. var temp_name = LocalizedStrings.getUI('new_function') + '_' + counter_new_functions;
  135. window.program_obj.functions.forEach(function(el) {
  136. if (temp_name == el.name) {
  137. in_use = true;
  138. }
  139. })
  140. if (in_use)
  141. counter_new_functions++;
  142. } while (in_use);
  143. }
  144. const new_function = new Models.Function(LocalizedStrings.getUI("new_function") + "_" + counter_new_functions, Types.VOID, 0, [], false, false, [], new Models.Comment(LocalizedStrings.getUI('text_comment_start')));
  145. program.addFunction(new_function);
  146. counter_new_functions ++;
  147. window.insertContext = true;
  148. registerUserEvent(new_function.name, ActionTypes.INSERT_FUNCTION);
  149. // var newe = renderFunction(new_function);
  150. renderFunction(new_function);
  151. /*newe.css('display', 'none');
  152. newe.fadeIn();*/
  153. }
  154. function addParameter (function_obj, function_container/*, is_from_click = false*/) {
  155. if (function_obj.parameters_list == null) {
  156. function_obj.parameters_list = [];
  157. }
  158. if (function_obj.parameters_list) {
  159. var in_use = false;
  160. do {
  161. in_use = false;
  162. var temp_name = LocalizedStrings.getUI('new_parameter') + '_' + counter_new_parameters;
  163. function_obj.parameters_list.forEach(function(el) {
  164. if (temp_name == el.name) {
  165. in_use = true;
  166. }
  167. })
  168. if (in_use)
  169. counter_new_parameters++;
  170. } while (in_use);
  171. }
  172. const new_parameter = new Models.Variable(Types.INTEGER, LocalizedStrings.getUI("new_parameter") + "_" + counter_new_parameters);
  173. function_obj.parameters_list.push(new_parameter);
  174. counter_new_parameters ++;
  175. registerUserEvent(function_obj.name, ActionTypes.INSERT_FUNCTION_PARAM, new_parameter.name, Types.INTEGER, 0);
  176. //var newe = renderParameter(function_obj, new_parameter, function_container);
  177. renderParameter(function_obj, new_parameter, function_container);
  178. // if (is_from_click) {
  179. // newe.css('display', 'none');
  180. // newe.fadeIn();
  181. // }
  182. }
  183. function updateReturnType (function_obj, new_type, new_dimensions = 0) {
  184. registerUserEvent(function_obj.name, ActionTypes.CHANGE_FUNCTION_RETURN, new_type, new_dimensions);
  185. function_obj.return_type = new_type;
  186. function_obj.return_dimensions = new_dimensions;
  187. }
  188. function removeFunction (function_obj) {
  189. var index = program.functions.indexOf(function_obj);
  190. if (index > -1) {
  191. registerUserEvent(function_obj.name, ActionTypes.REMOVE_FUNCTION);
  192. program.functions.splice(index, 1);
  193. }
  194. }
  195. function minimizeFunction (function_obj) {
  196. function_obj.is_hidden = !function_obj.is_hidden;
  197. }
  198. function addHandlers (function_obj, function_container) {
  199. function_container.find('.ui.dropdown.function_return').dropdown({
  200. onChange: function(value, text, $selectedItem) {
  201. if ($selectedItem.data('dimensions')) {
  202. updateReturnType(function_obj, Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
  203. } else {
  204. updateReturnType(function_obj, Types[$selectedItem.data('type')]);
  205. }
  206. },
  207. selectOnKeydown: false
  208. });
  209. function_container.find( ".name_function_updated" ).on('click', function(e){
  210. enableNameFunctionUpdate(function_obj, function_container);
  211. });
  212. function_container.find( ".add_parameter_button" ).on('click', function(e){
  213. window.insertContext = true;
  214. addParameter(function_obj, function_container, true);
  215. });
  216. function_container.find('.menu_commands').dropdown({
  217. on: 'hover'
  218. });
  219. function_container.find('.menu_commands a').on('click', function(evt){
  220. if (function_obj.commands == null || function_obj.commands.length == 0) {
  221. function_obj.commands = [];
  222. var new_cmd = CommandsManagement.genericCreateCommand($(this).data('command'));
  223. function_obj.commands.push(new_cmd);
  224. CommandsManagement.renderCommand(new_cmd, function_container.find('.commands_list_div'), 3, function_obj);
  225. registerUserEvent(function_obj.name, ActionTypes.INSERT_COMMAND, $(this).data('command'), '/', 0);
  226. } else {
  227. CommandsManagement.createFloatingCommand(function_obj, function_container, $(this).data('command'), evt);
  228. }
  229. });
  230. function_container.find('.add_var_button_function').on('click', function(e){
  231. window.insertContext = true;
  232. VariablesManagement.addVariable(function_obj, function_container, true);
  233. });
  234. function_container.find('.remove_function_button').on('click', function(e){
  235. removeFunction(function_obj);
  236. function_container.fadeOut();
  237. });
  238. function_container.find('.minimize_function_button').on('click', function(e){
  239. minimizeFunction(function_obj);
  240. if (function_obj.is_hidden) {
  241. function_container.find(".add_var_button_function").toggle();
  242. function_container.find(".inline_add_command").toggle();
  243. function_container.find(".function_area").slideToggle();
  244. } else {
  245. function_container.find(".function_area").slideToggle(function(){
  246. function_container.find(".add_var_button_function").toggle();
  247. function_container.find(".inline_add_command").toggle();
  248. });
  249. }
  250. });
  251. }
  252. // Essa função imprime o tipo de retorno da função e cria o menu do tipo 'select' para alteração
  253. function renderFunctionReturn (function_obj, function_element) {
  254. var ret = '<div class="ui dropdown function_return">';
  255. if (function_obj.return_dimensions == 1) {
  256. ret += '<div class="text">'+ LocalizedStrings.getUI("vector") +': '+ LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`);
  257. ret += ' [ ] </div>';
  258. } else if (function_obj.return_dimensions == 2) {
  259. ret += '<div class="text">'+ LocalizedStrings.getUI("matrix") +': '+ LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`);
  260. ret += ' [ ] [ ] </div>';
  261. } else {
  262. ret += '<div class="text">'+LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`)+'</div>';
  263. }
  264. ret += '<div class="menu">';
  265. for (var tm in Types) {
  266. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions < 1 ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  267. }
  268. ret += '<div class="item ' + (function_obj.return_dimensions == 1 ? ' selected ' : '') + '">'
  269. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('vector')
  270. + '<div class="menu">';
  271. for (var tm in Types) {
  272. if (tm == Types.VOID.toUpperCase()) {
  273. continue;
  274. }
  275. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions == 1 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="1"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  276. }
  277. ret += '</div></div>';
  278. ret += '<div class="item ' + (function_obj.return_dimensions == 2 ? ' selected ' : '') + '">'
  279. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('matrix')
  280. + '<div class="menu">';
  281. for (var tm in Types) {
  282. if (tm == Types.VOID.toUpperCase()) {
  283. continue;
  284. }
  285. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions == 2 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('matrix')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="2"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  286. }
  287. ret += '</div></div>';
  288. ret += '</div></div>';
  289. ret = $(ret);
  290. function_element.find('.function_return').append(ret);
  291. }
  292. var cont = 0;
  293. export function renderFunction (function_obj) {
  294. var appender = '<div class="ui secondary segment function_div list-group-item function_cont_'+cont+'">';
  295. if (function_obj.function_comment) {
  296. //appender += renderComment(function_obj.function_comment, sequence, true, -1);
  297. }
  298. appender += '<span class="glyphicon glyphicon-move move_function" aria-hidden="true"><i class="icon sort alternate vertical"></i></span>';
  299. appender += (function_obj.is_main ? '<div class="div_start_minimize_v"> </div>' : '<button class="ui icon button large remove_function_button"><i class="red icon times"></i></button>')
  300. + '<button class="ui icon button tiny minimize_function_button"><i class="icon window minimize"></i></button>';
  301. appender += '<div class="function_signature_div">'+LocalizedStrings.getUI("function")+' ';
  302. if (function_obj.is_main) {
  303. appender += '<div class="function_name_div"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + LocalizedStrings.getUI('type_void') + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="span_name_function" >'+function_obj.name+'</span> </div> '
  304. + ' <span class="parethesis_function">( </span> <div class="ui large labels parameters_list">';
  305. } else {
  306. appender += '<div class="ui function_return"></div>';
  307. appender += '<div class="function_name_div function_name_div_updated"><span class="span_name_function name_function_updated">'+function_obj.name+'</span> </div> '
  308. + ' <span class="parethesis_function"> ( </span> <i class="ui icon plus square outline add_parameter_button"></i> <div class="ui large labels parameters_list container_parameters_list">';
  309. }
  310. appender += '</div> <span class="parethesis_function"> ) </span> </div>'
  311. + (function_obj.is_hidden ? ' <div class="function_area" style="display: none;"> ' : ' <div class="function_area"> ');
  312. appender += '<div class="ui add_var_context add_var_button_function" style="float: left;"> <div class="ui icon button purple"> ';
  313. appender += '<i class="icons"><i class="icon superscript" style="margin-top: -2px;margin-bottom: 2px;margin-left: 1px;margin-right: 1px;"></i><i class="corner add icon inverted" style="font-size: 9px;padding-top: 6px;padding-left: 9px;"></i></i>';
  314. appender += '</div></div>';
  315. appender += '<div class="ui top attached segment variables_list_div"></div>';
  316. appender += '<div class="ui bottom attached segment commands_list_div commands_cont_'+cont+'">'
  317. + '<div class="ui rail" style="width: 35px; margin-left: -36px;"><div class="ui sticky sticky_cont_'+cont+'" style="top: 50px !important;">';
  318. appender += '<div class="ui icon button dropdown menu_commands orange" > '
  319. + '<i class="icons"><i class="icon code" style="margin-top: -1px;margin-bottom: 1px;margin-right: 0px;"></i><i class="corner add icon inverted" style="font-size: 9px;padding-top: 6px;padding-left: 9px;"></i></i>'
  320. + '<div class="menu"> ';
  321. appender += '<a class="item" data-command="'+Models.COMMAND_TYPES.reader+'"><i class="download icon"></i> ' +LocalizedStrings.getUI('text_read_var')+ '</a>'
  322. + '<a class="item" data-command="'+Models.COMMAND_TYPES.writer+'"><i class="upload icon"></i> '+LocalizedStrings.getUI('text_write_var')+'</a>'
  323. + '<a class="item" data-command="'+Models.COMMAND_TYPES.comment+'"><i class="quote left icon"></i> '+LocalizedStrings.getUI('text_comment')+'</a>'
  324. + '<a class="item" data-command="'+Models.COMMAND_TYPES.attribution+'"><i class="arrow left icon"></i> '+LocalizedStrings.getUI('text_attribution')+'</a>'
  325. + '<a class="item" data-command="'+Models.COMMAND_TYPES.functioncall+'"><i class="hand point right icon"></i> '+LocalizedStrings.getUI('text_functioncall')+'</a>'
  326. + '<a class="item" data-command="'+Models.COMMAND_TYPES.iftrue+'" ><i class="random icon"></i> '+LocalizedStrings.getUI('text_iftrue')+'</a>'
  327. + '<a class="item" data-command="'+Models.COMMAND_TYPES.repeatNtimes+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_repeatNtimes')+'</a>'
  328. + '<a class="item" data-command="'+Models.COMMAND_TYPES.whiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_whiletrue')+'</a>'
  329. + '<a class="item" data-command="'+Models.COMMAND_TYPES.dowhiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_dowhiletrue')+'</a>'
  330. + '<a class="item" data-command="'+Models.COMMAND_TYPES.switch+'"><i class="list icon"></i> '+LocalizedStrings.getUI('text_switch')+'</a>'
  331. + '<a class="item" data-command="'+Models.COMMAND_TYPES.return+'"><i class="reply icon"></i> '+LocalizedStrings.getUI('text_btn_return')+'</a>'
  332. + '</div></div>';
  333. appender += '</div></div>'
  334. +'</div>';
  335. appender += '</div></div>';
  336. appender = $(appender);
  337. $('.all_functions').append(appender);
  338. appender.data('fun', function_obj);
  339. appender.find('.commands_list_div').data('fun', function_obj);
  340. renderFunctionReturn(function_obj, appender);
  341. addHandlers(function_obj, appender);
  342. // Rendering parameters:
  343. for (var j = 0; j < function_obj.parameters_list.length; j++) {
  344. renderParameter(function_obj, function_obj.parameters_list[j], appender);
  345. }
  346. // Rendering variables:
  347. for (var j = 0; j < function_obj.variables_list.length; j++) {
  348. VariablesManagement.renderVariable(appender, function_obj.variables_list[j], function_obj);
  349. }
  350. // Rendering commands:
  351. for (var j = 0; j < function_obj.commands.length; j++) {
  352. CommandsManagement.renderCommand(function_obj.commands[j], $(appender.find('.commands_list_div')[0]), 3, function_obj);
  353. }
  354. appender.find('.minimize_function_button').popup({
  355. content : LocalizedStrings.getUI("tooltip_hide_function"),
  356. delay: {
  357. show: 750,
  358. hide: 0
  359. }
  360. });
  361. appender.find('.move_function').popup({
  362. content : LocalizedStrings.getUI("btn_drag_and_drop_function"),
  363. delay: {
  364. show: 1000,
  365. hide: 0
  366. }
  367. });
  368. appender.find('.remove_function_button').popup({
  369. content : LocalizedStrings.getUI("btn_delete_function"),
  370. delay: {
  371. show: 750,
  372. hide: 0
  373. }
  374. });
  375. appender.find('.add_var_button_function').popup({
  376. content : LocalizedStrings.getUI("btn_add_var"),
  377. delay: {
  378. show: 750,
  379. hide: 0
  380. }
  381. });
  382. appender.find('a[data-command="attribution"]').popup({
  383. content : LocalizedStrings.getUI("tooltip_menu_attribution"),
  384. position: 'right center',
  385. delay: {
  386. show: 750,
  387. hide: 0
  388. }
  389. });
  390. appender.find('a[data-command="functioncall"]').popup({
  391. content : LocalizedStrings.getUI("tooltip_menu_call_function"),
  392. position: 'right center',
  393. delay: {
  394. show: 750,
  395. hide: 0
  396. }
  397. });
  398. appender.find('a[data-command="iftrue"]').popup({
  399. content : LocalizedStrings.getUI("tooltip_menu_if_else"),
  400. position: 'right center',
  401. delay: {
  402. show: 750,
  403. hide: 0
  404. }
  405. });
  406. appender.find('a[data-command="comment"]').popup({
  407. content : LocalizedStrings.getUI("tooltip_menu_comments"),
  408. position: 'right center',
  409. delay: {
  410. show: 750,
  411. hide: 0
  412. }
  413. });
  414. appender.find('a[data-command="reader"]').popup({
  415. content : LocalizedStrings.getUI("tooltip_menu_read"),
  416. position: 'right center',
  417. delay: {
  418. show: 750,
  419. hide: 0
  420. }
  421. });
  422. appender.find('a[data-command="writer"]').popup({
  423. content : LocalizedStrings.getUI("tooltip_menu_write"),
  424. position: 'right center',
  425. delay: {
  426. show: 750,
  427. hide: 0
  428. }
  429. });
  430. appender.find('a[data-command="repeatNtimes"]').popup({
  431. content : LocalizedStrings.getUI("tooltip_menu_repeat_n_times"),
  432. position: 'right center',
  433. delay: {
  434. show: 750,
  435. hide: 0
  436. }
  437. });
  438. appender.find('a[data-command="whiletrue"]').popup({
  439. content : LocalizedStrings.getUI("tooltip_menu_repeat_whiletrue"),
  440. position: 'right center',
  441. delay: {
  442. show: 750,
  443. hide: 0
  444. }
  445. });
  446. appender.find('a[data-command="dowhiletrue"]').popup({
  447. content : LocalizedStrings.getUI("tooltip_menu_repeat_dowhiletrue"),
  448. position: 'right center',
  449. delay: {
  450. show: 750,
  451. hide: 0
  452. }
  453. });
  454. appender.find('a[data-command="switch"]').popup({
  455. content : LocalizedStrings.getUI("tooltip_menu_repeat_switch"),
  456. position: 'right center',
  457. delay: {
  458. show: 750,
  459. hide: 0
  460. }
  461. });
  462. appender.find('a[data-command="return"]').popup({
  463. content : LocalizedStrings.getUI("tooltip_menu_repeat_return"),
  464. position: 'right center',
  465. delay: {
  466. show: 750,
  467. hide: 0
  468. }
  469. });
  470. var function_index = program.functions.indexOf(function_obj);
  471. Sortable.create(appender.find(".variables_list_div")[0], {
  472. handle: '.ellipsis',
  473. animation: 100,
  474. ghostClass: 'ghost',
  475. group: 'local_vars_drag_' + function_index,
  476. onEnd: function (evt) {
  477. updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  478. }
  479. });
  480. addSortableHandler(appender.find(".commands_list_div")[0], function_index);
  481. if (!function_obj.is_main) {
  482. Sortable.create(appender.find(".container_parameters_list")[0], {
  483. handle: '.ellipsis',
  484. animation: 100,
  485. ghostClass: 'ghost',
  486. group: 'parameters_drag_' + program.functions.indexOf(function_obj),
  487. onEnd: function (evt) {
  488. updateSequenceParameters(evt.oldIndex, evt.newIndex, function_obj);
  489. }
  490. });
  491. }
  492. if (function_obj.commands.length > 0) {
  493. var teste = '.ui.sticky.sticky_cont_'+cont;
  494. $(teste).sticky({
  495. context: '.ui.bottom.attached.segment.commands_list_div.commands_cont_'+cont,
  496. scrollContext: '.ivprog_visual_panel',
  497. observeChanges: true,
  498. offset: 40,
  499. onStick: function (evt) {
  500. $(teste).css('top', '20px', 'important');
  501. },
  502. onBottom: function (evt) {
  503. $(teste).css('top', '20px', 'important');
  504. },
  505. onUnstick: function (evt) {
  506. $(teste).css('top', '20px', 'important');
  507. },
  508. onReposition: function (evt) {
  509. $(teste).css('top', '20px', 'important');
  510. },
  511. onScroll: function (evt) {
  512. $(teste).css('top', '20px', 'important');
  513. if (!isVisible($(teste), $(teste).parent())) {
  514. $(teste).removeClass('fixed');
  515. }
  516. },
  517. onTop: function (evt) {
  518. $(teste).css('top', '20px', 'important');
  519. }
  520. });
  521. }
  522. cont ++;
  523. appender.find('.add_parameter_button').popup({
  524. content : LocalizedStrings.getUI("text_add_parameters"),
  525. delay: {
  526. show: 750,
  527. hide: 0
  528. }
  529. });
  530. return appender;
  531. }
  532. function isVisible (element, container) {
  533. var elementTop = $(element).offset().top,
  534. elementHeight = $(element).height(),
  535. containerTop = $(container).offset().top,
  536. containerHeight = $(container).height() - 30;
  537. return ((((elementTop - containerTop) + elementHeight) > 0)
  538. && ((elementTop - containerTop) < containerHeight));
  539. }
  540. window.evento_drag;
  541. function updateProgramObjDrag () {
  542. const nodes = Array.prototype.slice.call( $('.all_functions').children() );
  543. let function_index;
  544. var start_index;
  545. let function_obj;
  546. $(evento_drag.item).parentsUntil(".all_functions").each(function (index) {
  547. const ref = $(this);
  548. if (ref.hasClass('function_div')) {
  549. function_index = nodes.indexOf(this);
  550. start_index = index;
  551. function_obj = ref;
  552. }
  553. });
  554. const path_target = [];
  555. $(evento_drag.item).parentsUntil(".all_functions").each(function () {
  556. if ($(this).hasClass('command_container')) {
  557. path_target.push(this);
  558. }
  559. });
  560. if (path_target.length == 0) {
  561. //console.log('soltou na raiz, na posição: ' + evento_drag.newIndex + ' mas ainda não sei de onde saiu ');
  562. } else {
  563. //console.log('soltou dentro de algum bloco, sequência vem logo abaixo (de baixo pra cima): ');
  564. //console.log(path_target);
  565. }
  566. var index_each = [];
  567. var path_relative = [];
  568. for (var i = path_target.length - 1; i >= 0; i --) {
  569. if (i == (path_target.length - 1)) { // está na raiz
  570. var indice_na_raiz = function_obj.find('.command_container').index(path_target[i]);
  571. } else {
  572. if ($(path_target[i + 1]).hasClass('iftrue')) {
  573. if ($(path_target[i]).parent().hasClass('commands_if')) {
  574. path_relative.push('if');
  575. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  576. } else {
  577. path_relative.push('else');
  578. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  579. }
  580. } else if ($(path_target[i + 1]).hasClass('dowhiletrue')) {
  581. path_relative.push('dowhiletrue');
  582. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  583. } else if ($(path_target[i + 1]).hasClass('repeatNtimes')) {
  584. path_relative.push('repeatNtimes');
  585. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  586. } else if ($(path_target[i + 1]).hasClass('whiletrue')) {
  587. path_relative.push('whiletrue');
  588. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  589. } else if ($(path_target[i + 1]).hasClass('switch')) {
  590. path_relative.push('switch');
  591. //index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  592. }
  593. }
  594. }
  595. // var index_in_block = -1;
  596. const is_in_else = $(evento_drag.item).parent().hasClass('commands_else');
  597. // index_in_block = $(evento_drag.item).parent().find('.command_container').index(evento_drag.item);
  598. const is_in_case_switch = $(evento_drag.item).parent().hasClass('case_commands_block');
  599. // encontrar o elemento na árvore:
  600. var command_start_point = window.program_obj.functions[function_index].commands[indice_na_raiz];
  601. var block_to_insert = command_start_point;
  602. for (var i = 0; i < index_each.length; i++) {
  603. if (path_relative[i] == "else") {
  604. block_to_insert = block_to_insert.commands_else[index_each[i]];
  605. } else if (path_relative[i] == "switch") {
  606. } else {
  607. block_to_insert = block_to_insert.commands_block[index_each[i]]
  608. }
  609. }
  610. //console.log('command_start_point', command_start_point);
  611. //console.log('block_to_insert', block_to_insert);
  612. // agora tem que alocar o comando na árvore, mas considerar as quatro situações:
  613. // (1) se está em um else ou (2) se está em switch ou (3) será um caso padrão ou (4) se será na raiz.
  614. if (path_target.length == 0) { // soltou na raiz:
  615. window.program_obj.functions[function_index].commands.splice(evento_drag.newIndex - 1, 0, command_in_drag);
  616. } else if (is_in_else) {
  617. if (block_to_insert.commands_else) {
  618. block_to_insert.commands_else.splice(evento_drag.newIndex, 0, command_in_drag);
  619. } else {
  620. block_to_insert.commands_else = [];
  621. block_to_insert.commands_else.push(command_in_drag);
  622. }
  623. } else if (is_in_case_switch) {
  624. } else {
  625. // verificar se tem alguma coisa no bloco:
  626. if (block_to_insert.commands_block) {
  627. block_to_insert.commands_block.splice(evento_drag.newIndex, 0, command_in_drag);
  628. } else {
  629. block_to_insert.commands_block = [];
  630. block_to_insert.commands_block.push(command_in_drag);
  631. }
  632. }
  633. window.draging = false;
  634. renderAlgorithm();
  635. }
  636. function prepareDragHandler (evt) {
  637. window.draging = true;
  638. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  639. var function_index;
  640. var function_obj;
  641. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  642. if ($(this).hasClass('function_div')) {
  643. function_index = nodes.indexOf(this);
  644. function_obj = window.program_obj.functions[function_index];
  645. }
  646. });
  647. command_in_drag = $(evt.item).data("command");
  648. //console.log('$(evt.item).parent(): ');
  649. //console.log($(evt.item).parent());
  650. // descobrir qual das quatro situações:
  651. if ($(evt.item).parent().hasClass('commands_list_div')) { // está na raiz:
  652. if (function_obj.commands.indexOf(command_in_drag) > -1) {
  653. function_obj.commands.splice(function_obj.commands.indexOf(command_in_drag), 1);
  654. }
  655. } else if ($(evt.item).parent().hasClass('commands_else')) { // está no else:
  656. if ($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag) > -1) {
  657. $(evt.item).parent().data('command').commands_else.splice($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag), 1);
  658. }
  659. } else if ($(evt.item).parent().hasClass('case_commands_block')) { // está em um switch:
  660. } else { // caso padrão:
  661. if ($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag) > -1) {
  662. $(evt.item).parent().data('command').commands_block.splice($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag), 1);
  663. }
  664. }
  665. }
  666. var command_in_drag;
  667. function addSortableHandler (element, id_function) {
  668. var n_group = 'commands_drag_' + id_function;
  669. Sortable.create(element, {
  670. handle: '.command_drag',
  671. ghostClass: 'ghost',
  672. animation: 300,
  673. group: {name: n_group},
  674. onEnd: function (evt) {
  675. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  676. var function_index;
  677. var function_obj;
  678. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  679. if ($(this).hasClass('function_div')) {
  680. function_index = nodes.indexOf(this);
  681. function_obj = window.program_obj.functions[function_index];
  682. }
  683. });
  684. registerUserEvent(function_obj.name, ActionTypes.MOVE_COMMAND, $(evt.item).data('command').type, '/', 'from: ' + evt.oldIndex + ' to: ' + evt.newIndex);
  685. //updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  686. var itemEl = evt.item; // dragged HTMLElement
  687. evt.to; // target list
  688. evt.from; // previous list
  689. evt.oldIndex; // element's old index within old parent
  690. evt.newIndex; // element's new index within new parent
  691. //console.log('::EVT::');
  692. //console.log(evt);
  693. window.evento_drag = evt;
  694. try {
  695. updateProgramObjDrag();
  696. } catch (e) {
  697. console.error(e);
  698. window.draging = false;
  699. }
  700. },
  701. onStart: function (evt) {
  702. //console.log("START::EVT::");
  703. //console.log(evt);
  704. //console.log("\n\ncommand_in_drag");
  705. try {
  706. prepareDragHandler(evt);
  707. } catch (e) {
  708. window.draging = false;
  709. }
  710. }
  711. });
  712. element = $(element);
  713. element.find(".iftrue").each(function( index ) {
  714. addSortableHandler($(this).find(".block_commands")[0], id_function);
  715. addSortableHandler($(this).find(".block_commands")[1], id_function);
  716. });
  717. element.find(".repeatNtimes").each(function( index ) {
  718. addSortableHandler($(this).find(".block_commands")[0], id_function);
  719. });
  720. element.find(".dowhiletrue").each(function( index ) {
  721. addSortableHandler($(this).find(".block_commands")[0], id_function);
  722. });
  723. element.find(".whiletrue").each(function( index ) {
  724. addSortableHandler($(this).find(".block_commands")[0], id_function);
  725. });
  726. element.find(".switch").each(function( index ) {
  727. $(this).find(".case_div").each(function( index ) {
  728. addSortableHandler($(this).find(".case_commands_block")[0], id_function);
  729. });
  730. });
  731. }
  732. export function initVisualUI () {
  733. // MUST USE CONST, LET, OR VAR !!!!!!
  734. // const mainDiv = $('#visual-main-div');
  735. // fill mainDiv with functions and globals...
  736. // renderAlgorithm()...
  737. domConsole = new DOMConsole("ivprog-term-div");
  738. domConsole.hide();
  739. $(document.getElementById("ivprog-term-div")).draggable()
  740. $('.add_function_button').on('click', () => {
  741. addFunctionHandler();
  742. }).popup({
  743. content : LocalizedStrings.getUI("text_add_function"),
  744. delay: {
  745. show: 750,
  746. hide: 0
  747. }
  748. });
  749. $('.add_global_button').on('click', () => {
  750. window.insertContext = true;
  751. GlobalsManagement.addGlobal(program, true);
  752. });
  753. $('#run_button').on('click', function () {
  754. showStopButton();
  755. runCode();
  756. });
  757. $('#download_file_button').on('click', function () {
  758. downloadFile();
  759. });
  760. $('#upload_file_button').on('click', function () {
  761. $('#ivph_file').click().off('change').change(uploadFile);
  762. });
  763. $('#stop_button').on('click', function () {
  764. showRunButton();
  765. stopExecution();
  766. });
  767. $('.visual_coding_button').on('click', () => {
  768. toggleVisualCoding();
  769. });
  770. $('.textual_coding_button').on('click', () => {
  771. toggleTextualCoding();
  772. });
  773. $('.assessment').on('click', () => {
  774. is_iassign = true;
  775. runCodeAssessment();
  776. });
  777. $('.div_toggle_console').on('click', () => {
  778. toggleConsole();
  779. });
  780. $('.expand_button').on('click', () => {
  781. full_screen();
  782. });
  783. $('.help_button').on('click', () => {
  784. window.open('https://www.usp.br/line/ivprog/', '_blank');
  785. });
  786. $('.main_title h2').prop('title', LocalizedStrings.getUI('text_ivprog_description'));
  787. var time_show = 750;
  788. $('.visual_coding_button').popup({
  789. content : LocalizedStrings.getUI("tooltip_visual"),
  790. delay: {
  791. show: time_show,
  792. hide: 0
  793. }
  794. });
  795. $('.textual_coding_button').popup({
  796. content : LocalizedStrings.getUI("tooltip_textual"),
  797. delay: {
  798. show: time_show,
  799. hide: 0
  800. }
  801. });
  802. $('.upload_file_button').popup({
  803. content : LocalizedStrings.getUI("tooltip_upload"),
  804. delay: {
  805. show: time_show,
  806. hide: 0
  807. }
  808. });
  809. $('.download_file_button').popup({
  810. content : LocalizedStrings.getUI("tooltip_download"),
  811. delay: {
  812. show: time_show,
  813. hide: 0
  814. }
  815. });
  816. $('.undo_button').popup({
  817. content : LocalizedStrings.getUI("tooltip_undo"),
  818. delay: {
  819. show: time_show,
  820. hide: 0
  821. }
  822. });
  823. $('.redo_button').popup({
  824. content : LocalizedStrings.getUI("tooltip_redo"),
  825. delay: {
  826. show: time_show,
  827. hide: 0
  828. }
  829. });
  830. $('.run_button').popup({
  831. content : LocalizedStrings.getUI("tooltip_run"),
  832. delay: {
  833. show: time_show,
  834. hide: 0
  835. }
  836. });
  837. $('.assessment_button').popup({
  838. content : LocalizedStrings.getUI("tooltip_evaluate"),
  839. delay: {
  840. show: time_show,
  841. hide: 0
  842. }
  843. });
  844. $('.help_button').popup({
  845. content : LocalizedStrings.getUI("tooltip_help") + ' - ' + LocalizedStrings.getUI("text_ivprog_version") + ' ' + ivprog_version,
  846. delay: {
  847. show: time_show,
  848. hide: 0
  849. }
  850. });
  851. $('.add_global_button').popup({
  852. content : LocalizedStrings.getUI("tooltip_add_global"),
  853. delay: {
  854. show: time_show,
  855. hide: 0
  856. }
  857. });
  858. $('.div_toggle_console').popup({
  859. content : LocalizedStrings.getUI("tooltip_console"),
  860. delay: {
  861. show: time_show,
  862. hide: 0
  863. }
  864. });
  865. Sortable.create(listWithHandle, {
  866. handle: '.glyphicon-move',
  867. animation: 100,
  868. ghostClass: 'ghost',
  869. group: 'functions_divs_drag',
  870. onEnd: function (evt) {
  871. updateSequenceFunction(evt.oldIndex, evt.newIndex);
  872. }
  873. });
  874. var listGlobalsHandle = document.getElementById("listGlobalsHandle");
  875. Sortable.create(listGlobalsHandle, {
  876. handle: '.ellipsis',
  877. animation: 100,
  878. ghostClass: 'ghost',
  879. group: 'globals_divs_drag',
  880. onEnd: function (evt) {
  881. updateSequenceGlobals(evt.oldIndex, evt.newIndex);
  882. }
  883. });
  884. }
  885. export function setTestCases (testCases) {
  886. _testCases = testCases;
  887. }
  888. export function getTestCases () {
  889. // Deep clone of test cases to avoid unauthorized modification
  890. // TODO: It may be not possible to use this once custom test are fully implemented
  891. return JSON.parse(JSON.stringify(_testCases));
  892. }
  893. var is_iassign = false;
  894. function updateSequenceParameters (oldIndex, newIndex, function_obj) {
  895. function_obj.parameters_list.splice(newIndex, 0, function_obj.parameters_list.splice(oldIndex, 1)[0]);
  896. }
  897. function updateSequenceLocals (oldIndex, newIndex, function_obj) {
  898. function_obj.variables_list.splice(newIndex, 0, function_obj.variables_list.splice(oldIndex, 1)[0]);
  899. }
  900. function updateSequenceGlobals (oldIndex, newIndex) {
  901. program_obj.globals.splice(newIndex, 0, program_obj.globals.splice(oldIndex, 1)[0]);
  902. }
  903. function updateSequenceFunction (oldIndex, newIndex) {
  904. program_obj.functions.splice(newIndex, 0, program_obj.functions.splice(oldIndex, 1)[0]);
  905. }
  906. function runCodeAssessment () {
  907. if (isRunning) {
  908. // cannot run assessment or it's already running
  909. return -1;
  910. }
  911. let strCode = null;
  912. is_iassign = false;
  913. window.studentGrade = null;
  914. if (settingsProgrammingTypes == "textual") {
  915. strCode = TextEditor.getCode();
  916. } else {
  917. strCode = CodeManagement.generate();
  918. }
  919. if (strCode == null) {
  920. // No code, so no assessment
  921. return -1;
  922. }
  923. toggleConsole(true);
  924. try {
  925. const data = SemanticAnalyser.analyseFromSource(strCode);
  926. isRunning = true;
  927. const runner = new IVProgAssessment(data, _testCases, domConsole);
  928. runner.runTest().then(grade => {
  929. if (!is_iassign) {
  930. parent.getEvaluationCallback(grade);
  931. } else {
  932. is_iassign = false;
  933. }
  934. isRunning = false;
  935. }).catch( err => {
  936. console.log(err);
  937. isRunning = false;
  938. });
  939. } catch (error) {
  940. isRunning = false;
  941. domConsole.err(error.message);
  942. console.log(error);
  943. if (!is_iassign) {
  944. parent.getEvaluationCallback(0);
  945. } else {
  946. is_iassign = false;
  947. }
  948. }
  949. return 0;
  950. }
  951. function runCode () {
  952. if (isRunning) {
  953. return;
  954. }
  955. let strCode = null;
  956. if (settingsProgrammingTypes == "textual") {
  957. strCode = TextEditor.getCode();
  958. } else {
  959. strCode = CodeManagement.generate();
  960. }
  961. if (strCode == null) {
  962. return;
  963. }
  964. toggleConsole(true);
  965. // if(domConsole == null)
  966. // domConsole = new DOMConsole("#ivprog-term");
  967. //$("#ivprog-term").slideDown(500);
  968. try {
  969. const data = SemanticAnalyser.analyseFromSource(strCode);
  970. proc = new IVProgProcessor(data);
  971. proc.registerInput(domConsole);
  972. proc.registerOutput(domConsole);
  973. $("#ivprog-term").addClass('ivprog-term-active');
  974. isRunning = true;
  975. proc.interpretAST().then( _ => {
  976. scheduleCall(() => {
  977. if(domConsole.pending_writes.length == 0) {
  978. if(proc.mode === Modes.ABORT) {
  979. domConsole.info(LocalizedStrings.getMessage("aborted_execution"));
  980. } else {
  981. domConsole.info(LocalizedStrings.getMessage("success_execution"));
  982. }
  983. $("#ivprog-term").removeClass('ivprog-term-active');
  984. isRunning = false;
  985. proc = null;
  986. showRunButton();
  987. return true;
  988. }
  989. return false;
  990. },100);
  991. }).catch(err => {
  992. scheduleCall(() => {
  993. if(domConsole.pending_writes.length == 0) {
  994. if(err instanceof Error) {
  995. domConsole.err(err.message);
  996. } else {
  997. domConsole.err(err);
  998. }
  999. $("#ivprog-term").removeClass('ivprog-term-active');
  1000. isRunning = false;
  1001. proc = null;
  1002. showRunButton();
  1003. return true;
  1004. }
  1005. return false;
  1006. },100);
  1007. })
  1008. } catch (error) {
  1009. scheduleCall(() => {
  1010. if(domConsole.pending_writes.length == 0) {
  1011. isRunning = false;
  1012. proc = null;
  1013. showRunButton();
  1014. domConsole.err(error.message);
  1015. console.log(error);
  1016. return true;
  1017. }
  1018. return false;
  1019. },100);
  1020. }
  1021. }
  1022. function toggleConsole (is_running) {
  1023. if (is_running) {
  1024. $('.ivprog-term-div').css('display', 'block');
  1025. $('#ivprog-term').css('min-height', '160px');
  1026. if(domConsole != null)
  1027. domConsole.focus();
  1028. //$('#ivprog-term').css('margin-top', '-170px');
  1029. return;
  1030. } else {
  1031. domConsole.hide();
  1032. return;
  1033. }
  1034. if ($('#ivprog-term').css('min-height') == '160px') {
  1035. // esconder
  1036. $('.ivprog-term-div').css('display', 'none');
  1037. $('#ivprog-term').css('min-height', '0');
  1038. //$('#ivprog-term').css('margin-top', '-30px');
  1039. //$('#ivprog-term').css('padding', '5px');
  1040. } else {
  1041. // mostrar
  1042. $('.ivprog-term-div').css('display', 'block');
  1043. $('#ivprog-term').css('min-height', '160px');
  1044. //$('#ivprog-term').css('margin-top', '-170px');
  1045. }
  1046. }
  1047. // function waitToCloseConsole () {
  1048. // domConsole.info("Aperte qualquer tecla para fechar...");
  1049. // const p = new Promise((resolve, _) => {
  1050. // domConsole.requestInput(resolve, true);
  1051. // });
  1052. // p.then( _ => {
  1053. // domConsole.dispose();
  1054. // domConsole = null;
  1055. // $("#ivprog-term").hide();
  1056. // })
  1057. // }
  1058. function toggleTextualCoding () {
  1059. let code = null;
  1060. if (settingsProgrammingTypes != "textual") {
  1061. code = CodeManagement.generate();
  1062. if (code == null) {
  1063. return;
  1064. }
  1065. }
  1066. $('.ivprog_visual_panel').css('display', 'none');
  1067. $('.ivprog_textual_panel').css('display', 'block');
  1068. $('.ivprog_textual_panel').removeClass('loading');
  1069. TextEditor.updateEditor();
  1070. if (code != null)
  1071. TextEditor.setCode(code);
  1072. //$('.ivprog_textual_code').text(code);
  1073. $('.visual_coding_button').removeClass('active');
  1074. $('.textual_coding_button').addClass('active');
  1075. }
  1076. function toggleVisualCoding () {
  1077. $('.ivprog_textual_panel').addClass('loading');
  1078. $('.ivprog_textual_panel').css('display', 'none');
  1079. $('.ivprog_visual_panel').css('display', 'block');
  1080. $('.textual_coding_button').removeClass('active');
  1081. $('.visual_coding_button').addClass('active');
  1082. }
  1083. function removeParameter (function_obj, parameter_obj, parameter_container) {
  1084. registerUserEvent(parameter_obj.name, ActionTypes.REMOVE_FUNCTION_PARAM, function_obj.name);
  1085. var index = function_obj.parameters_list.indexOf(parameter_obj);
  1086. if (index > -1) {
  1087. window.insertContext = true;
  1088. function_obj.parameters_list.splice(index, 1);
  1089. }
  1090. $(parameter_container).fadeOut();
  1091. }
  1092. function updateParameterType (parameter_obj, new_type, function_name, new_dimensions = 0) {
  1093. registerUserEvent(parameter_obj.name, ActionTypes.CHANGE_PARAM_TYPE, function_name, new_type, new_dimensions);
  1094. parameter_obj.type = new_type;
  1095. parameter_obj.dimensions = new_dimensions;
  1096. if (new_dimensions > 0) {
  1097. parameter_obj.rows = new_dimensions;
  1098. parameter_obj.columns = 2;
  1099. }
  1100. }
  1101. function renderParameter (function_obj, parameter_obj, function_container) {
  1102. let ret = "";
  1103. ret += '<div class="ui label function_name_parameter pink"><i class="ui icon ellipsis vertical inverted"></i>';
  1104. if (parameter_obj.reference)
  1105. ret += '<input type="checkbox" checked class="by_reference">';
  1106. else
  1107. ret += '<input type="checkbox" class="by_copy">';
  1108. ret += '<div class="ui dropdown parameter_type">';
  1109. if (parameter_obj.dimensions > 0) {
  1110. ret += '<div class="text">'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${parameter_obj.type.toLowerCase()}`);
  1111. if (parameter_obj.dimensions == 1) {
  1112. ret += ' [ ] ';
  1113. } else {
  1114. ret += ' [ ] [ ] ';
  1115. }
  1116. ret += '</div>';
  1117. } else {
  1118. ret += '<div class="text">'+LocalizedStrings.getUI(`type_${parameter_obj.type.toLowerCase()}`)+'</div>';
  1119. }
  1120. ret += '<div class="menu">';
  1121. for (const tm in Types) {
  1122. if (tm == Types.VOID.toUpperCase()) {
  1123. continue;
  1124. }
  1125. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 0 ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  1126. }
  1127. ret += '<div class="item ' + (parameter_obj.dimensions == 1 ? ' selected ' : '') + '">'
  1128. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('vector')
  1129. + '<div class="menu">';
  1130. for (var tm in Types) {
  1131. if (tm == Types.VOID.toUpperCase()) {
  1132. continue;
  1133. }
  1134. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 1 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="1"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  1135. }
  1136. ret += '</div></div>';
  1137. ret += '<div class="item ' + (parameter_obj.dimensions == 2 ? ' selected ' : '') + '">'
  1138. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('matrix')
  1139. + '<div class="menu">';
  1140. for (var tm in Types) {
  1141. if (tm == Types.VOID.toUpperCase()) {
  1142. continue;
  1143. }
  1144. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 2 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('matrix')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="2"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  1145. }
  1146. ret += '</div></div>';
  1147. ret += '</div></div>';
  1148. ret += '<div class="parameter_div_edit"><span class="span_name_parameter label_enable_name_parameter">'+parameter_obj.name+'</span></div> ';
  1149. ret += ' <i class="yellow inverted icon times remove_parameter"></i></div>';
  1150. ret = $(ret);
  1151. function_container.find('.container_parameters_list').append(ret);
  1152. ret.find('.remove_parameter').on('click', function(e){
  1153. removeParameter(function_obj, parameter_obj, ret);
  1154. });
  1155. ret.find('.ui.dropdown.parameter_type').dropdown({
  1156. onChange: function(_, __, $selectedItem) {
  1157. if ($selectedItem.data('dimensions')) {
  1158. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name, $selectedItem.data('dimensions'));
  1159. } else {
  1160. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name);
  1161. }
  1162. },
  1163. selectOnKeydown: false
  1164. });
  1165. ret.find('.parameter_div_edit').on('click', function(e){
  1166. registerUserEvent(function_obj.name, ActionTypes.ENTER_CHANGE_PARAM_NAME, parameter_obj.name);
  1167. enableNameParameterUpdate(parameter_obj, ret, function_obj);
  1168. });
  1169. ret.find('input:checkbox').change(function() {
  1170. parameter_obj.reference = this.checked
  1171. AlgorithmManagement.renderAlgorithm();
  1172. });
  1173. ret.find('.by_reference').popup({
  1174. content : LocalizedStrings.getUI("text_parameter_reference"),
  1175. delay: {
  1176. show: 750,
  1177. hide: 0
  1178. }
  1179. });
  1180. ret.find('.by_copy').popup({
  1181. content : LocalizedStrings.getUI("text_parameter_copy"),
  1182. delay: {
  1183. show: 750,
  1184. hide: 0
  1185. }
  1186. });
  1187. return ret;
  1188. }
  1189. function updateParameterName (parameter_var, new_name, parameter_obj_dom, function_obj) {
  1190. if (parameter_var.name == new_name) {
  1191. return;
  1192. }
  1193. if (isValidIdentifier(new_name)) {
  1194. if (variableNameAlreadyExists(new_name, function_obj)) {
  1195. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getError('inform_valid_param_duplicated', [new_name, function_obj.name]));
  1196. } else {
  1197. registerUserEvent(function_obj.name, ActionTypes.RENAME_FUNCTION_PARAM, parameter_var.name, new_name);
  1198. parameter_var.name = new_name;
  1199. }
  1200. } else {
  1201. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getError('inform_valid_identifier'));
  1202. }
  1203. }
  1204. function variableNameAlreadyExists (name_var, function_obj) {
  1205. if (function_obj.parameters_list) {
  1206. for (var i = 0; i < function_obj.parameters_list.length; i++) {
  1207. if (function_obj.parameters_list[i].name == name_var) {
  1208. return true;
  1209. }
  1210. }
  1211. }
  1212. if (function_obj.variables_list) {
  1213. for (var i = 0; i < function_obj.variables_list.length; i++) {
  1214. if (function_obj.variables_list[i].name == name_var) {
  1215. return true;
  1216. }
  1217. }
  1218. }
  1219. return false;
  1220. }
  1221. function updateFunctionName (function_var, new_name, function_obj_dom) {
  1222. if (function_var.name == new_name) {
  1223. return;
  1224. }
  1225. if (isValidIdentifier(new_name)) {
  1226. if (functionNameAlreadyExists(new_name)) {
  1227. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getError('inform_valid_function_duplicated', [new_name]));
  1228. } else {
  1229. registerUserEvent(function_var.name, ActionTypes.RENAME_FUNCTION, new_name);
  1230. function_var.name = new_name;
  1231. }
  1232. } else {
  1233. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getError('inform_valid_identifier'));
  1234. }
  1235. }
  1236. function functionNameAlreadyExists (function_name) {
  1237. for (var i = 0; i < window.program_obj.functions.length; i++) {
  1238. if (window.program_obj.functions[i].name == function_name) {
  1239. return true;
  1240. }
  1241. }
  1242. return false;
  1243. }
  1244. var opened_name_parameter = false;
  1245. var opened_input_parameter = null;
  1246. function enableNameParameterUpdate (parameter_obj, parent_node, function_obj) {
  1247. if (opened_name_parameter) {
  1248. opened_input_parameter.focus();
  1249. return;
  1250. }
  1251. opened_name_parameter = true;
  1252. parent_node = $(parent_node);
  1253. var input_field;
  1254. parent_node.find('.span_name_parameter').text('');
  1255. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+parameter_obj.name+"' />" );
  1256. input_field.insertBefore(parent_node.find('.span_name_parameter'));
  1257. input_field.on('input', function() {
  1258. var inputWidth = input_field.textWidth()+10;
  1259. opened_input_parameter = input_field;
  1260. input_field.focus();
  1261. var tmpStr = input_field.val();
  1262. input_field.val('');
  1263. input_field.val(tmpStr);
  1264. input_field.css({
  1265. width: inputWidth
  1266. })
  1267. }).trigger('input');
  1268. input_field.focusout(function() {
  1269. /// update array:
  1270. if (input_field.val().trim()) {
  1271. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1272. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1273. }
  1274. input_field.off();
  1275. input_field.remove();
  1276. /// update elements:
  1277. opened_name_parameter = false;
  1278. opened_input_parameter = false;
  1279. });
  1280. input_field.on('keydown', function(e) {
  1281. var code = e.keyCode || e.which;
  1282. if(code == 13) {
  1283. if (input_field.val().trim()) {
  1284. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1285. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1286. }
  1287. input_field.off();
  1288. input_field.remove();
  1289. /// update elements:
  1290. opened_name_parameter = false;
  1291. opened_input_parameter = false;
  1292. }
  1293. if(code == 27) {
  1294. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1295. input_field.off();
  1296. input_field.remove();
  1297. /// update elements:
  1298. opened_name_parameter = false;
  1299. opened_input_parameter = false;
  1300. }
  1301. });
  1302. input_field.select();
  1303. }
  1304. var opened_name_function = false;
  1305. var opened_input = null;
  1306. var previousPadding = null;
  1307. function enableNameFunctionUpdate (function_obj, parent_node) {
  1308. if (opened_name_function) {
  1309. opened_input.focus();
  1310. return;
  1311. }
  1312. parent_node = $(parent_node);
  1313. parent_node.find('.span_name_function').text('');
  1314. var input_field;
  1315. if (!previousPadding) {
  1316. previousPadding = parent_node.find('.span_name_function').css('padding-left');
  1317. }
  1318. parent_node.find('.span_name_function').css('padding-left', '0');
  1319. parent_node.find('.span_name_function').css('padding-right', '0');
  1320. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+function_obj.name+"' />" );
  1321. input_field.insertBefore(parent_node.find('.span_name_function'));
  1322. input_field.on('input', function() {
  1323. var inputWidth = input_field.textWidth()+10;
  1324. opened_input = input_field;
  1325. input_field.focus();
  1326. var tmpStr = input_field.val();
  1327. input_field.val('');
  1328. input_field.val(tmpStr);
  1329. input_field.css({
  1330. width: inputWidth
  1331. })
  1332. }).trigger('input');
  1333. input_field.focusout(function() {
  1334. /// update array:
  1335. if (input_field.val().trim()) {
  1336. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1337. }
  1338. input_field.off();
  1339. input_field.remove();
  1340. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1341. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1342. parent_node.find('.span_name_function').text(function_obj.name);
  1343. /// update elements:
  1344. opened_name_function = false;
  1345. opened_input = false;
  1346. });
  1347. input_field.on('keydown', function(e) {
  1348. var code = e.keyCode || e.which;
  1349. if(code == 13) {
  1350. if (input_field.val().trim()) {
  1351. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1352. }
  1353. input_field.off();
  1354. input_field.remove();
  1355. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1356. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1357. parent_node.find('.span_name_function').text(function_obj.name);
  1358. /// update elements:
  1359. opened_name_function = false;
  1360. opened_input = false;
  1361. }
  1362. if(code == 27) {
  1363. input_field.off();
  1364. input_field.remove();
  1365. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1366. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1367. parent_node.find('.span_name_function').text(function_obj.name);
  1368. /// update elements:
  1369. opened_name_function = false;
  1370. opened_input = false;
  1371. }
  1372. });
  1373. input_field.select();
  1374. }
  1375. export function addFunctionChangeListener (callback) {
  1376. functionsChangeListeners.push(callback);
  1377. return functionsChangeListeners.length - 1;
  1378. }
  1379. export function addGlobalChangeListener (callback) {
  1380. globalChangeListeners.push(callback);
  1381. return globalChangeListeners.length - 1;
  1382. }
  1383. export function removeGlobalListener (index) {
  1384. globalChangeListeners.splice(index, 1);
  1385. }
  1386. export function removeFunctionListener (index) {
  1387. functionsChangeListeners.splice(index);
  1388. }
  1389. function scheduleCall (callback, time) {
  1390. const scheduled_call = () => {
  1391. const id = setInterval(() => {
  1392. if(callback()) {
  1393. clearInterval(id);
  1394. }
  1395. }, time)
  1396. }
  1397. scheduled_call();
  1398. }
  1399. function showRunButton () {
  1400. document.getElementById('run_button').style.display = 'inline';
  1401. document.getElementById('stop_button').style.display = 'none';
  1402. }
  1403. function showStopButton () {
  1404. document.getElementById('run_button').style.display = 'none';
  1405. document.getElementById('stop_button').style.display = 'inline';
  1406. }
  1407. function stopExecution () {
  1408. domConsole.clearPendingWrites();
  1409. domConsole.cancelPendingInputRequests();
  1410. if(!isRunning) {
  1411. return;
  1412. }
  1413. proc.mode = Modes.ABORT;
  1414. }
  1415. function downloadFile() {
  1416. var contentToSend = '{}\n::algorithm::';
  1417. contentToSend = generator();
  1418. var date = new Date();
  1419. var temp = date.toISOString().split('T')[0] + "_" + date.toTimeString().split(' ')[0].replaceAll(':', '-');
  1420. var blob = new Blob([contentToSend],
  1421. { type: "text/plain;charset=utf-8" });
  1422. saveAs(blob, "ivprog-exported_" + temp + ".ivph");
  1423. }
  1424. function uploadFile (evt) {
  1425. var oFReader = new FileReader();
  1426. oFReader.readAsText(document.getElementById("ivph_file").files[0]);
  1427. oFReader.onload = function (oFREvent) {
  1428. var txt = oFREvent.target.result;
  1429. try {
  1430. ivprogCore.setPreviousAlgorithm(txt);
  1431. window.renderAlgorithm();
  1432. }
  1433. catch (e) {
  1434. showInvalidFile();
  1435. }
  1436. };
  1437. }