functions.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  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. if (txt.indexOf("::algorithm::") >= 0 || txt.indexOf("\"test_cases\"") >= 0) {
  1431. //leo/lucas Version with "test-cases": { "version": "x.y",\n "code": ... \n "test_cases":...
  1432. prepareActivityToStudent(txt, true);
  1433. console.debug("code=" + txt.code):
  1434. } else {
  1435. ivprogCore.setPreviousAlgorithm(txt);
  1436. window.renderAlgorithm();
  1437. }
  1438. }
  1439. catch (e) {
  1440. console.log(e)
  1441. }
  1442. };
  1443. }