functions.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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. 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')));
  131. program.addFunction(new_function);
  132. counter_new_functions ++;
  133. window.insertContext = true;
  134. registerUserEvent(new_function.name, ActionTypes.INSERT_FUNCTION);
  135. // var newe = renderFunction(new_function);
  136. renderFunction(new_function);
  137. /*newe.css('display', 'none');
  138. newe.fadeIn();*/
  139. }
  140. function addParameter (function_obj, function_container/*, is_from_click = false*/) {
  141. if (function_obj.parameters_list == null) {
  142. function_obj.parameters_list = [];
  143. }
  144. const new_parameter = new Models.Variable(Types.INTEGER, LocalizedStrings.getUI("new_parameter") + "_" + counter_new_parameters);
  145. function_obj.parameters_list.push(new_parameter);
  146. counter_new_parameters ++;
  147. registerUserEvent(function_obj.name, ActionTypes.INSERT_FUNCTION_PARAM, new_parameter.name, Types.INTEGER, 0);
  148. //var newe = renderParameter(function_obj, new_parameter, function_container);
  149. renderParameter(function_obj, new_parameter, function_container);
  150. // if (is_from_click) {
  151. // newe.css('display', 'none');
  152. // newe.fadeIn();
  153. // }
  154. }
  155. function updateReturnType (function_obj, new_type, new_dimensions = 0) {
  156. registerUserEvent(function_obj.name, ActionTypes.CHANGE_FUNCTION_RETURN, new_type, new_dimensions);
  157. function_obj.return_type = new_type;
  158. function_obj.return_dimensions = new_dimensions;
  159. }
  160. function removeFunction (function_obj) {
  161. var index = program.functions.indexOf(function_obj);
  162. if (index > -1) {
  163. registerUserEvent(function_obj.name, ActionTypes.REMOVE_FUNCTION);
  164. program.functions.splice(index, 1);
  165. }
  166. }
  167. function minimizeFunction (function_obj) {
  168. function_obj.is_hidden = !function_obj.is_hidden;
  169. }
  170. function addHandlers (function_obj, function_container) {
  171. function_container.find('.ui.dropdown.function_return').dropdown({
  172. onChange: function(value, text, $selectedItem) {
  173. if ($selectedItem.data('dimensions')) {
  174. updateReturnType(function_obj, Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
  175. } else {
  176. updateReturnType(function_obj, Types[$selectedItem.data('type')]);
  177. }
  178. },
  179. selectOnKeydown: false
  180. });
  181. function_container.find( ".name_function_updated" ).on('click', function(e){
  182. enableNameFunctionUpdate(function_obj, function_container);
  183. });
  184. function_container.find( ".add_parameter_button" ).on('click', function(e){
  185. window.insertContext = true;
  186. addParameter(function_obj, function_container, true);
  187. });
  188. function_container.find('.menu_commands').dropdown({
  189. on: 'hover'
  190. });
  191. function_container.find('.menu_commands a').on('click', function(evt){
  192. if (function_obj.commands == null || function_obj.commands.length == 0) {
  193. function_obj.commands = [];
  194. var new_cmd = CommandsManagement.genericCreateCommand($(this).data('command'));
  195. function_obj.commands.push(new_cmd);
  196. CommandsManagement.renderCommand(new_cmd, function_container.find('.commands_list_div'), 3, function_obj);
  197. registerUserEvent(function_obj.name, ActionTypes.INSERT_COMMAND, $(this).data('command'), '/', 0);
  198. } else {
  199. CommandsManagement.createFloatingCommand(function_obj, function_container, $(this).data('command'), evt);
  200. }
  201. });
  202. function_container.find('.add_var_button_function').on('click', function(e){
  203. window.insertContext = true;
  204. VariablesManagement.addVariable(function_obj, function_container, true);
  205. });
  206. function_container.find('.remove_function_button').on('click', function(e){
  207. removeFunction(function_obj);
  208. function_container.fadeOut();
  209. });
  210. function_container.find('.minimize_function_button').on('click', function(e){
  211. minimizeFunction(function_obj);
  212. if (function_obj.is_hidden) {
  213. function_container.find(".add_var_button_function").toggle();
  214. function_container.find(".inline_add_command").toggle();
  215. function_container.find(".function_area").slideToggle();
  216. } else {
  217. function_container.find(".function_area").slideToggle(function(){
  218. function_container.find(".add_var_button_function").toggle();
  219. function_container.find(".inline_add_command").toggle();
  220. });
  221. }
  222. });
  223. }
  224. // Essa função imprime o tipo de retorno da função e cria o menu do tipo 'select' para alteração
  225. function renderFunctionReturn (function_obj, function_element) {
  226. var ret = '<div class="ui dropdown function_return">';
  227. if (function_obj.return_dimensions == 1) {
  228. ret += '<div class="text">'+ LocalizedStrings.getUI("vector") +': '+ LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`);
  229. ret += ' [ ] </div>';
  230. } else if (function_obj.return_dimensions == 2) {
  231. ret += '<div class="text">'+ LocalizedStrings.getUI("matrix") +': '+ LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`);
  232. ret += ' [ ] [ ] </div>';
  233. } else {
  234. ret += '<div class="text">'+LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`)+'</div>';
  235. }
  236. ret += '<div class="menu">';
  237. for (var tm in Types) {
  238. 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>';
  239. }
  240. ret += '<div class="item ' + (function_obj.return_dimensions == 1 ? ' selected ' : '') + '">'
  241. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('vector')
  242. + '<div class="menu">';
  243. for (var tm in Types) {
  244. if (tm == Types.VOID.toUpperCase()) {
  245. continue;
  246. }
  247. 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>';
  248. }
  249. ret += '</div></div>';
  250. ret += '<div class="item ' + (function_obj.return_dimensions == 2 ? ' selected ' : '') + '">'
  251. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('matrix')
  252. + '<div class="menu">';
  253. for (var tm in Types) {
  254. if (tm == Types.VOID.toUpperCase()) {
  255. continue;
  256. }
  257. 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>';
  258. }
  259. ret += '</div></div>';
  260. ret += '</div></div>';
  261. ret = $(ret);
  262. function_element.find('.function_return').append(ret);
  263. }
  264. var cont = 0;
  265. export function renderFunction (function_obj) {
  266. var appender = '<div class="ui secondary segment function_div list-group-item function_cont_'+cont+'">';
  267. if (function_obj.function_comment) {
  268. //appender += renderComment(function_obj.function_comment, sequence, true, -1);
  269. }
  270. appender += '<span class="glyphicon glyphicon-move move_function" aria-hidden="true"><i class="icon sort alternate vertical"></i></span>';
  271. 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>')
  272. + '<button class="ui icon button tiny minimize_function_button"><i class="icon window minimize"></i></button>';
  273. appender += '<div class="function_signature_div">'+LocalizedStrings.getUI("function")+' ';
  274. if (function_obj.is_main) {
  275. 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> '
  276. + ' <span class="parethesis_function">( </span> <div class="ui large labels parameters_list">';
  277. } else {
  278. appender += '<div class="ui function_return"></div>';
  279. appender += '<div class="function_name_div function_name_div_updated"><span class="span_name_function name_function_updated">'+function_obj.name+'</span> </div> '
  280. + ' <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">';
  281. }
  282. appender += '</div> <span class="parethesis_function"> ) </span> </div>'
  283. + (function_obj.is_hidden ? ' <div class="function_area" style="display: none;"> ' : ' <div class="function_area"> ');
  284. appender += '<div class="ui add_var_context add_var_button_function" style="float: left;"> <div class="ui icon button purple"> ';
  285. 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>';
  286. appender += '</div></div>';
  287. appender += '<div class="ui top attached segment variables_list_div"></div>';
  288. appender += '<div class="ui bottom attached segment commands_list_div commands_cont_'+cont+'">'
  289. + '<div class="ui rail" style="width: 35px; margin-left: -36px;"><div class="ui sticky sticky_cont_'+cont+'" style="top: 50px !important;">';
  290. appender += '<div class="ui icon button dropdown menu_commands orange" > '
  291. + '<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>'
  292. + '<div class="menu"> ';
  293. appender += '<a class="item" data-command="'+Models.COMMAND_TYPES.reader+'"><i class="download icon"></i> ' +LocalizedStrings.getUI('text_read_var')+ '</a>'
  294. + '<a class="item" data-command="'+Models.COMMAND_TYPES.writer+'"><i class="upload icon"></i> '+LocalizedStrings.getUI('text_write_var')+'</a>'
  295. + '<a class="item" data-command="'+Models.COMMAND_TYPES.comment+'"><i class="quote left icon"></i> '+LocalizedStrings.getUI('text_comment')+'</a>'
  296. + '<a class="item" data-command="'+Models.COMMAND_TYPES.attribution+'"><i class="arrow left icon"></i> '+LocalizedStrings.getUI('text_attribution')+'</a>'
  297. + '<a class="item" data-command="'+Models.COMMAND_TYPES.functioncall+'"><i class="hand point right icon"></i> '+LocalizedStrings.getUI('text_functioncall')+'</a>'
  298. + '<a class="item" data-command="'+Models.COMMAND_TYPES.iftrue+'" ><i class="random icon"></i> '+LocalizedStrings.getUI('text_iftrue')+'</a>'
  299. + '<a class="item" data-command="'+Models.COMMAND_TYPES.repeatNtimes+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_repeatNtimes')+'</a>'
  300. + '<a class="item" data-command="'+Models.COMMAND_TYPES.whiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_whiletrue')+'</a>'
  301. + '<a class="item" data-command="'+Models.COMMAND_TYPES.dowhiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_dowhiletrue')+'</a>'
  302. + '<a class="item" data-command="'+Models.COMMAND_TYPES.switch+'"><i class="list icon"></i> '+LocalizedStrings.getUI('text_switch')+'</a>'
  303. + '<a class="item" data-command="'+Models.COMMAND_TYPES.return+'"><i class="reply icon"></i> '+LocalizedStrings.getUI('text_btn_return')+'</a>'
  304. + '</div></div>';
  305. appender += '</div></div>'
  306. +'</div>';
  307. appender += '</div></div>';
  308. appender = $(appender);
  309. $('.all_functions').append(appender);
  310. appender.data('fun', function_obj);
  311. appender.find('.commands_list_div').data('fun', function_obj);
  312. renderFunctionReturn(function_obj, appender);
  313. addHandlers(function_obj, appender);
  314. // Rendering parameters:
  315. for (var j = 0; j < function_obj.parameters_list.length; j++) {
  316. renderParameter(function_obj, function_obj.parameters_list[j], appender);
  317. }
  318. // Rendering variables:
  319. for (var j = 0; j < function_obj.variables_list.length; j++) {
  320. VariablesManagement.renderVariable(appender, function_obj.variables_list[j], function_obj);
  321. }
  322. // Rendering commands:
  323. for (var j = 0; j < function_obj.commands.length; j++) {
  324. CommandsManagement.renderCommand(function_obj.commands[j], $(appender.find('.commands_list_div')[0]), 3, function_obj);
  325. }
  326. $('.minimize_function_button').popup({
  327. content : LocalizedStrings.getUI("tooltip_hide_function"),
  328. delay: {
  329. show: 750,
  330. hide: 0
  331. }
  332. });
  333. var function_index = program.functions.indexOf(function_obj);
  334. Sortable.create(appender.find(".variables_list_div")[0], {
  335. handle: '.ellipsis',
  336. animation: 100,
  337. ghostClass: 'ghost',
  338. group: 'local_vars_drag_' + function_index,
  339. onEnd: function (evt) {
  340. updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  341. }
  342. });
  343. addSortableHandler(appender.find(".commands_list_div")[0], function_index);
  344. if (!function_obj.is_main) {
  345. Sortable.create(appender.find(".container_parameters_list")[0], {
  346. handle: '.ellipsis',
  347. animation: 100,
  348. ghostClass: 'ghost',
  349. group: 'parameters_drag_' + program.functions.indexOf(function_obj),
  350. onEnd: function (evt) {
  351. updateSequenceParameters(evt.oldIndex, evt.newIndex, function_obj);
  352. }
  353. });
  354. }
  355. if (function_obj.commands.length > 0) {
  356. var teste = '.ui.sticky.sticky_cont_'+cont;
  357. $(teste).sticky({
  358. context: '.ui.bottom.attached.segment.commands_list_div.commands_cont_'+cont,
  359. scrollContext: '.ivprog_visual_panel',
  360. observeChanges: true,
  361. offset: 40,
  362. onStick: function (evt) {
  363. $(teste).css('top', '20px', 'important');
  364. },
  365. onBottom: function (evt) {
  366. $(teste).css('top', '20px', 'important');
  367. },
  368. onUnstick: function (evt) {
  369. $(teste).css('top', '20px', 'important');
  370. },
  371. onReposition: function (evt) {
  372. $(teste).css('top', '20px', 'important');
  373. },
  374. onScroll: function (evt) {
  375. $(teste).css('top', '20px', 'important');
  376. if (!isVisible($(teste), $(teste).parent())) {
  377. $(teste).removeClass('fixed');
  378. }
  379. },
  380. onTop: function (evt) {
  381. $(teste).css('top', '20px', 'important');
  382. }
  383. });
  384. }
  385. cont ++;
  386. return appender;
  387. }
  388. function isVisible (element, container) {
  389. var elementTop = $(element).offset().top,
  390. elementHeight = $(element).height(),
  391. containerTop = $(container).offset().top,
  392. containerHeight = $(container).height() - 30;
  393. return ((((elementTop - containerTop) + elementHeight) > 0)
  394. && ((elementTop - containerTop) < containerHeight));
  395. }
  396. window.evento_drag;
  397. function updateProgramObjDrag () {
  398. const nodes = Array.prototype.slice.call( $('.all_functions').children() );
  399. let function_index;
  400. var start_index;
  401. let function_obj;
  402. $(evento_drag.item).parentsUntil(".all_functions").each(function (index) {
  403. const ref = $(this);
  404. if (ref.hasClass('function_div')) {
  405. function_index = nodes.indexOf(this);
  406. start_index = index;
  407. function_obj = ref;
  408. }
  409. });
  410. const path_target = [];
  411. $(evento_drag.item).parentsUntil(".all_functions").each(function () {
  412. if ($(this).hasClass('command_container')) {
  413. path_target.push(this);
  414. }
  415. });
  416. if (path_target.length == 0) {
  417. //console.log('soltou na raiz, na posição: ' + evento_drag.newIndex + ' mas ainda não sei de onde saiu ');
  418. } else {
  419. //console.log('soltou dentro de algum bloco, sequência vem logo abaixo (de baixo pra cima): ');
  420. //console.log(path_target);
  421. }
  422. var index_each = [];
  423. var path_relative = [];
  424. for (var i = path_target.length - 1; i >= 0; i --) {
  425. if (i == (path_target.length - 1)) { // está na raiz
  426. var indice_na_raiz = function_obj.find('.command_container').index(path_target[i]);
  427. } else {
  428. if ($(path_target[i + 1]).hasClass('iftrue')) {
  429. if ($(path_target[i]).parent().hasClass('commands_if')) {
  430. path_relative.push('if');
  431. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  432. } else {
  433. path_relative.push('else');
  434. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  435. }
  436. } else if ($(path_target[i + 1]).hasClass('dowhiletrue')) {
  437. path_relative.push('dowhiletrue');
  438. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  439. } else if ($(path_target[i + 1]).hasClass('repeatNtimes')) {
  440. path_relative.push('repeatNtimes');
  441. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  442. } else if ($(path_target[i + 1]).hasClass('whiletrue')) {
  443. path_relative.push('whiletrue');
  444. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  445. } else if ($(path_target[i + 1]).hasClass('switch')) {
  446. path_relative.push('switch');
  447. //index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  448. }
  449. }
  450. }
  451. // var index_in_block = -1;
  452. const is_in_else = $(evento_drag.item).parent().hasClass('commands_else');
  453. // index_in_block = $(evento_drag.item).parent().find('.command_container').index(evento_drag.item);
  454. const is_in_case_switch = $(evento_drag.item).parent().hasClass('case_commands_block');
  455. // encontrar o elemento na árvore:
  456. var command_start_point = window.program_obj.functions[function_index].commands[indice_na_raiz];
  457. var block_to_insert = command_start_point;
  458. for (var i = 0; i < index_each.length; i++) {
  459. if (path_relative[i] == "else") {
  460. block_to_insert = block_to_insert.commands_else[index_each[i]];
  461. } else if (path_relative[i] == "switch") {
  462. } else {
  463. block_to_insert = block_to_insert.commands_block[index_each[i]]
  464. }
  465. }
  466. //console.log('command_start_point', command_start_point);
  467. //console.log('block_to_insert', block_to_insert);
  468. // agora tem que alocar o comando na árvore, mas considerar as quatro situações:
  469. // (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.
  470. if (path_target.length == 0) { // soltou na raiz:
  471. window.program_obj.functions[function_index].commands.splice(evento_drag.newIndex - 1, 0, command_in_drag);
  472. } else if (is_in_else) {
  473. if (block_to_insert.commands_else) {
  474. block_to_insert.commands_else.splice(evento_drag.newIndex, 0, command_in_drag);
  475. } else {
  476. block_to_insert.commands_else = [];
  477. block_to_insert.commands_else.push(command_in_drag);
  478. }
  479. } else if (is_in_case_switch) {
  480. } else {
  481. // verificar se tem alguma coisa no bloco:
  482. if (block_to_insert.commands_block) {
  483. block_to_insert.commands_block.splice(evento_drag.newIndex, 0, command_in_drag);
  484. } else {
  485. block_to_insert.commands_block = [];
  486. block_to_insert.commands_block.push(command_in_drag);
  487. }
  488. }
  489. window.draging = false;
  490. renderAlgorithm();
  491. }
  492. function prepareDragHandler (evt) {
  493. window.draging = true;
  494. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  495. var function_index;
  496. var function_obj;
  497. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  498. if ($(this).hasClass('function_div')) {
  499. function_index = nodes.indexOf(this);
  500. function_obj = window.program_obj.functions[function_index];
  501. }
  502. });
  503. command_in_drag = $(evt.item).data("command");
  504. //console.log('$(evt.item).parent(): ');
  505. //console.log($(evt.item).parent());
  506. // descobrir qual das quatro situações:
  507. if ($(evt.item).parent().hasClass('commands_list_div')) { // está na raiz:
  508. if (function_obj.commands.indexOf(command_in_drag) > -1) {
  509. function_obj.commands.splice(function_obj.commands.indexOf(command_in_drag), 1);
  510. }
  511. } else if ($(evt.item).parent().hasClass('commands_else')) { // está no else:
  512. if ($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag) > -1) {
  513. $(evt.item).parent().data('command').commands_else.splice($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag), 1);
  514. }
  515. } else if ($(evt.item).parent().hasClass('case_commands_block')) { // está em um switch:
  516. } else { // caso padrão:
  517. if ($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag) > -1) {
  518. $(evt.item).parent().data('command').commands_block.splice($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag), 1);
  519. }
  520. }
  521. }
  522. var command_in_drag;
  523. function addSortableHandler (element, id_function) {
  524. var n_group = 'commands_drag_' + id_function;
  525. Sortable.create(element, {
  526. handle: '.command_drag',
  527. ghostClass: 'ghost',
  528. animation: 300,
  529. group: {name: n_group},
  530. onEnd: function (evt) {
  531. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  532. var function_index;
  533. var function_obj;
  534. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  535. if ($(this).hasClass('function_div')) {
  536. function_index = nodes.indexOf(this);
  537. function_obj = window.program_obj.functions[function_index];
  538. }
  539. });
  540. registerUserEvent(function_obj.name, ActionTypes.MOVE_COMMAND, $(evt.item).data('command').type, '/', 'from: ' + evt.oldIndex + ' to: ' + evt.newIndex);
  541. //updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  542. var itemEl = evt.item; // dragged HTMLElement
  543. evt.to; // target list
  544. evt.from; // previous list
  545. evt.oldIndex; // element's old index within old parent
  546. evt.newIndex; // element's new index within new parent
  547. //console.log('::EVT::');
  548. //console.log(evt);
  549. window.evento_drag = evt;
  550. try {
  551. updateProgramObjDrag();
  552. } catch (e) {
  553. console.error(e);
  554. window.draging = false;
  555. }
  556. },
  557. onStart: function (evt) {
  558. //console.log("START::EVT::");
  559. //console.log(evt);
  560. //console.log("\n\ncommand_in_drag");
  561. try {
  562. prepareDragHandler(evt);
  563. } catch (e) {
  564. window.draging = false;
  565. }
  566. }
  567. });
  568. element = $(element);
  569. element.find(".iftrue").each(function( index ) {
  570. addSortableHandler($(this).find(".block_commands")[0], id_function);
  571. addSortableHandler($(this).find(".block_commands")[1], id_function);
  572. });
  573. element.find(".repeatNtimes").each(function( index ) {
  574. addSortableHandler($(this).find(".block_commands")[0], id_function);
  575. });
  576. element.find(".dowhiletrue").each(function( index ) {
  577. addSortableHandler($(this).find(".block_commands")[0], id_function);
  578. });
  579. element.find(".whiletrue").each(function( index ) {
  580. addSortableHandler($(this).find(".block_commands")[0], id_function);
  581. });
  582. element.find(".switch").each(function( index ) {
  583. $(this).find(".case_div").each(function( index ) {
  584. addSortableHandler($(this).find(".case_commands_block")[0], id_function);
  585. });
  586. });
  587. }
  588. export function initVisualUI () {
  589. // MUST USE CONST, LET, OR VAR !!!!!!
  590. // const mainDiv = $('#visual-main-div');
  591. // fill mainDiv with functions and globals...
  592. // renderAlgorithm()...
  593. domConsole = new DOMConsole("ivprog-term-div");
  594. domConsole.hide();
  595. $(document.getElementById("ivprog-term-div")).draggable()
  596. $('.add_function_button').on('click', () => {
  597. addFunctionHandler();
  598. });
  599. $('.add_global_button').on('click', () => {
  600. window.insertContext = true;
  601. GlobalsManagement.addGlobal(program, true);
  602. });
  603. $('#run_button').on('click', function () {
  604. showStopButton();
  605. runCode();
  606. });
  607. $('#stop_button').on('click', function () {
  608. showRunButton();
  609. stopExecution();
  610. });
  611. $('.visual_coding_button').on('click', () => {
  612. toggleVisualCoding();
  613. });
  614. $('.textual_coding_button').on('click', () => {
  615. toggleTextualCoding();
  616. });
  617. $('.assessment').on('click', () => {
  618. is_iassign = true;
  619. runCodeAssessment();
  620. });
  621. $('.div_toggle_console').on('click', () => {
  622. toggleConsole();
  623. });
  624. $('.expand_button').on('click', () => {
  625. full_screen();
  626. });
  627. $('.help_button').on('click', () => {
  628. window.open('https://www.usp.br/line/ivprog/', '_blank');
  629. });
  630. $('.main_title h2').prop('title', LocalizedStrings.getUI('text_ivprog_description'));
  631. var time_show = 750;
  632. $('.visual_coding_button').popup({
  633. content : LocalizedStrings.getUI("tooltip_visual"),
  634. delay: {
  635. show: time_show,
  636. hide: 0
  637. }
  638. });
  639. $('.textual_coding_button').popup({
  640. content : LocalizedStrings.getUI("tooltip_textual"),
  641. delay: {
  642. show: time_show,
  643. hide: 0
  644. }
  645. });
  646. $('.upload_file_button').popup({
  647. content : LocalizedStrings.getUI("tooltip_upload"),
  648. delay: {
  649. show: time_show,
  650. hide: 0
  651. }
  652. });
  653. $('.download_file_button').popup({
  654. content : LocalizedStrings.getUI("tooltip_download"),
  655. delay: {
  656. show: time_show,
  657. hide: 0
  658. }
  659. });
  660. $('.undo_button').popup({
  661. content : LocalizedStrings.getUI("tooltip_undo"),
  662. delay: {
  663. show: time_show,
  664. hide: 0
  665. }
  666. });
  667. $('.redo_button').popup({
  668. content : LocalizedStrings.getUI("tooltip_redo"),
  669. delay: {
  670. show: time_show,
  671. hide: 0
  672. }
  673. });
  674. $('.run_button').popup({
  675. content : LocalizedStrings.getUI("tooltip_run"),
  676. delay: {
  677. show: time_show,
  678. hide: 0
  679. }
  680. });
  681. $('.assessment_button').popup({
  682. content : LocalizedStrings.getUI("tooltip_evaluate"),
  683. delay: {
  684. show: time_show,
  685. hide: 0
  686. }
  687. });
  688. $('.help_button').popup({
  689. content : LocalizedStrings.getUI("tooltip_help") + ' - ' + LocalizedStrings.getUI("text_ivprog_version") + ' ' + ivprog_version,
  690. delay: {
  691. show: time_show,
  692. hide: 0
  693. }
  694. });
  695. $('.add_global_button').popup({
  696. content : LocalizedStrings.getUI("tooltip_add_global"),
  697. delay: {
  698. show: time_show,
  699. hide: 0
  700. }
  701. });
  702. $('.div_toggle_console').popup({
  703. content : LocalizedStrings.getUI("tooltip_console"),
  704. delay: {
  705. show: time_show,
  706. hide: 0
  707. }
  708. });
  709. Sortable.create(listWithHandle, {
  710. handle: '.glyphicon-move',
  711. animation: 100,
  712. ghostClass: 'ghost',
  713. group: 'functions_divs_drag',
  714. onEnd: function (evt) {
  715. updateSequenceFunction(evt.oldIndex, evt.newIndex);
  716. }
  717. });
  718. var listGlobalsHandle = document.getElementById("listGlobalsHandle");
  719. Sortable.create(listGlobalsHandle, {
  720. handle: '.ellipsis',
  721. animation: 100,
  722. ghostClass: 'ghost',
  723. group: 'globals_divs_drag',
  724. onEnd: function (evt) {
  725. updateSequenceGlobals(evt.oldIndex, evt.newIndex);
  726. }
  727. });
  728. }
  729. export function setTestCases (testCases) {
  730. _testCases = testCases;
  731. }
  732. export function getTestCases () {
  733. // Deep clone of test cases to avoid unauthorized modification
  734. // TODO: It may be not possible to use this once custom test are fully implemented
  735. return JSON.parse(JSON.stringify(_testCases));
  736. }
  737. var is_iassign = false;
  738. function updateSequenceParameters (oldIndex, newIndex, function_obj) {
  739. function_obj.parameters_list.splice(newIndex, 0, function_obj.parameters_list.splice(oldIndex, 1)[0]);
  740. }
  741. function updateSequenceLocals (oldIndex, newIndex, function_obj) {
  742. function_obj.variables_list.splice(newIndex, 0, function_obj.variables_list.splice(oldIndex, 1)[0]);
  743. }
  744. function updateSequenceGlobals (oldIndex, newIndex) {
  745. program_obj.globals.splice(newIndex, 0, program_obj.globals.splice(oldIndex, 1)[0]);
  746. }
  747. function updateSequenceFunction (oldIndex, newIndex) {
  748. program_obj.functions.splice(newIndex, 0, program_obj.functions.splice(oldIndex, 1)[0]);
  749. }
  750. function runCodeAssessment () {
  751. if (isRunning) {
  752. // cannot run assessment or it's already running
  753. return -1;
  754. }
  755. let strCode = null;
  756. is_iassign = false;
  757. window.studentGrade = null;
  758. if (settingsProgrammingTypes == "textual") {
  759. strCode = TextEditor.getCode();
  760. } else {
  761. strCode = CodeManagement.generate();
  762. }
  763. if (strCode == null) {
  764. // No code, so no assessment
  765. return -1;
  766. }
  767. toggleConsole(true);
  768. try {
  769. const data = SemanticAnalyser.analyseFromSource(strCode);
  770. isRunning = true;
  771. const runner = new IVProgAssessment(data, _testCases, domConsole);
  772. runner.runTest().then(grade => {
  773. if (!is_iassign) {
  774. parent.getEvaluationCallback(grade);
  775. } else {
  776. is_iassign = false;
  777. }
  778. isRunning = false;
  779. }).catch( err => {
  780. console.log(err);
  781. isRunning = false;
  782. });
  783. } catch (error) {
  784. isRunning = false;
  785. domConsole.err(error.message);
  786. console.log(error);
  787. if (!is_iassign) {
  788. parent.getEvaluationCallback(0);
  789. } else {
  790. is_iassign = false;
  791. }
  792. }
  793. return 0;
  794. }
  795. function runCode () {
  796. if (isRunning) {
  797. return;
  798. }
  799. let strCode = null;
  800. if (settingsProgrammingTypes == "textual") {
  801. strCode = TextEditor.getCode();
  802. } else {
  803. strCode = CodeManagement.generate();
  804. }
  805. if (strCode == null) {
  806. return;
  807. }
  808. toggleConsole(true);
  809. // if(domConsole == null)
  810. // domConsole = new DOMConsole("#ivprog-term");
  811. //$("#ivprog-term").slideDown(500);
  812. try {
  813. const data = SemanticAnalyser.analyseFromSource(strCode);
  814. proc = new IVProgProcessor(data);
  815. proc.registerInput(domConsole);
  816. proc.registerOutput(domConsole);
  817. $("#ivprog-term").addClass('ivprog-term-active');
  818. isRunning = true;
  819. proc.interpretAST().then( _ => {
  820. scheduleCall(() => {
  821. if(domConsole.pending_writes.length == 0) {
  822. if(proc.mode === Modes.ABORT) {
  823. domConsole.info(LocalizedStrings.getMessage("aborted_execution"));
  824. } else {
  825. domConsole.info(LocalizedStrings.getMessage("success_execution"));
  826. }
  827. $("#ivprog-term").removeClass('ivprog-term-active');
  828. isRunning = false;
  829. proc = null;
  830. showRunButton();
  831. return true;
  832. }
  833. return false;
  834. },100);
  835. }).catch(err => {
  836. scheduleCall(() => {
  837. if(domConsole.pending_writes.length == 0) {
  838. if(err instanceof Error) {
  839. domConsole.err(err.message);
  840. } else {
  841. domConsole.err(err);
  842. }
  843. $("#ivprog-term").removeClass('ivprog-term-active');
  844. isRunning = false;
  845. proc = null;
  846. showRunButton();
  847. return true;
  848. }
  849. return false;
  850. },100);
  851. })
  852. } catch (error) {
  853. scheduleCall(() => {
  854. if(domConsole.pending_writes.length == 0) {
  855. isRunning = false;
  856. proc = null;
  857. showRunButton();
  858. domConsole.err(error.message);
  859. console.log(error);
  860. return true;
  861. }
  862. return false;
  863. },100);
  864. }
  865. }
  866. function toggleConsole (is_running) {
  867. if (is_running) {
  868. $('.ivprog-term-div').css('display', 'block');
  869. $('#ivprog-term').css('min-height', '160px');
  870. if(domConsole != null)
  871. domConsole.focus();
  872. //$('#ivprog-term').css('margin-top', '-170px');
  873. return;
  874. } else {
  875. domConsole.hide();
  876. return;
  877. }
  878. if ($('#ivprog-term').css('min-height') == '160px') {
  879. // esconder
  880. $('.ivprog-term-div').css('display', 'none');
  881. $('#ivprog-term').css('min-height', '0');
  882. //$('#ivprog-term').css('margin-top', '-30px');
  883. //$('#ivprog-term').css('padding', '5px');
  884. } else {
  885. // mostrar
  886. $('.ivprog-term-div').css('display', 'block');
  887. $('#ivprog-term').css('min-height', '160px');
  888. //$('#ivprog-term').css('margin-top', '-170px');
  889. }
  890. }
  891. // function waitToCloseConsole () {
  892. // domConsole.info("Aperte qualquer tecla para fechar...");
  893. // const p = new Promise((resolve, _) => {
  894. // domConsole.requestInput(resolve, true);
  895. // });
  896. // p.then( _ => {
  897. // domConsole.dispose();
  898. // domConsole = null;
  899. // $("#ivprog-term").hide();
  900. // })
  901. // }
  902. function toggleTextualCoding () {
  903. let code = null;
  904. if (settingsProgrammingTypes != "textual") {
  905. code = CodeManagement.generate();
  906. if (code == null) {
  907. return;
  908. }
  909. }
  910. $('.ivprog_visual_panel').css('display', 'none');
  911. $('.ivprog_textual_panel').css('display', 'block');
  912. $('.ivprog_textual_panel').removeClass('loading');
  913. TextEditor.updateEditor();
  914. if (code != null)
  915. TextEditor.setCode(code);
  916. //$('.ivprog_textual_code').text(code);
  917. $('.visual_coding_button').removeClass('active');
  918. $('.textual_coding_button').addClass('active');
  919. }
  920. function toggleVisualCoding () {
  921. $('.ivprog_textual_panel').addClass('loading');
  922. $('.ivprog_textual_panel').css('display', 'none');
  923. $('.ivprog_visual_panel').css('display', 'block');
  924. $('.textual_coding_button').removeClass('active');
  925. $('.visual_coding_button').addClass('active');
  926. }
  927. function removeParameter (function_obj, parameter_obj, parameter_container) {
  928. registerUserEvent(parameter_obj.name, ActionTypes.REMOVE_FUNCTION_PARAM, function_obj.name);
  929. var index = function_obj.parameters_list.indexOf(parameter_obj);
  930. if (index > -1) {
  931. window.insertContext = true;
  932. function_obj.parameters_list.splice(index, 1);
  933. }
  934. $(parameter_container).fadeOut();
  935. }
  936. function updateParameterType (parameter_obj, new_type, function_name, new_dimensions = 0) {
  937. registerUserEvent(parameter_obj.name, ActionTypes.CHANGE_PARAM_TYPE, function_name, new_type, new_dimensions);
  938. parameter_obj.type = new_type;
  939. parameter_obj.dimensions = new_dimensions;
  940. if (new_dimensions > 0) {
  941. parameter_obj.rows = new_dimensions;
  942. parameter_obj.columns = 2;
  943. }
  944. }
  945. function renderParameter (function_obj, parameter_obj, function_container) {
  946. let ret = "";
  947. ret += '<div class="ui label function_name_parameter pink"><i class="ui icon ellipsis vertical inverted"></i>';
  948. ret += '<div class="ui dropdown parameter_type">';
  949. if (parameter_obj.dimensions > 0) {
  950. ret += '<div class="text">'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${parameter_obj.type.toLowerCase()}`);
  951. if (parameter_obj.dimensions == 1) {
  952. ret += ' [ ] ';
  953. } else {
  954. ret += ' [ ] [ ] ';
  955. }
  956. ret += '</div>';
  957. } else {
  958. ret += '<div class="text">'+LocalizedStrings.getUI(`type_${parameter_obj.type.toLowerCase()}`)+'</div>';
  959. }
  960. ret += '<div class="menu">';
  961. for (const tm in Types) {
  962. if (tm == Types.VOID.toUpperCase()) {
  963. continue;
  964. }
  965. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 0 ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  966. }
  967. ret += '<div class="item ' + (parameter_obj.dimensions == 1 ? ' selected ' : '') + '">'
  968. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('vector')
  969. + '<div class="menu">';
  970. for (var tm in Types) {
  971. if (tm == Types.VOID.toUpperCase()) {
  972. continue;
  973. }
  974. 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>';
  975. }
  976. ret += '</div></div>';
  977. ret += '<div class="item ' + (parameter_obj.dimensions == 2 ? ' selected ' : '') + '">'
  978. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('matrix')
  979. + '<div class="menu">';
  980. for (var tm in Types) {
  981. if (tm == Types.VOID.toUpperCase()) {
  982. continue;
  983. }
  984. 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>';
  985. }
  986. ret += '</div></div>';
  987. ret += '</div></div>';
  988. ret += '<div class="parameter_div_edit"><span class="span_name_parameter label_enable_name_parameter">'+parameter_obj.name+'</span></div> ';
  989. ret += ' <i class="yellow inverted icon times remove_parameter"></i></div>';
  990. ret = $(ret);
  991. function_container.find('.container_parameters_list').append(ret);
  992. ret.find('.remove_parameter').on('click', function(e){
  993. removeParameter(function_obj, parameter_obj, ret);
  994. });
  995. ret.find('.ui.dropdown.parameter_type').dropdown({
  996. onChange: function(_, __, $selectedItem) {
  997. if ($selectedItem.data('dimensions')) {
  998. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name, $selectedItem.data('dimensions'));
  999. } else {
  1000. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name);
  1001. }
  1002. },
  1003. selectOnKeydown: false
  1004. });
  1005. ret.find('.parameter_div_edit').on('click', function(e){
  1006. registerUserEvent(function_obj.name, ActionTypes.ENTER_CHANGE_PARAM_NAME, parameter_obj.name);
  1007. enableNameParameterUpdate(parameter_obj, ret, function_obj);
  1008. });
  1009. return ret;
  1010. }
  1011. function updateParameterName (parameter_var, new_name, parameter_obj_dom, function_obj) {
  1012. if (parameter_var.name == new_name) {
  1013. return;
  1014. }
  1015. if (isValidIdentifier(new_name)) {
  1016. if (variableNameAlreadyExists(new_name, function_obj)) {
  1017. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getError('inform_valid_param_duplicated', [new_name, function_obj.name]));
  1018. } else {
  1019. registerUserEvent(function_obj.name, ActionTypes.RENAME_FUNCTION_PARAM, parameter_var.name, new_name);
  1020. parameter_var.name = new_name;
  1021. }
  1022. } else {
  1023. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getError('inform_valid_identifier'));
  1024. }
  1025. }
  1026. function variableNameAlreadyExists (name_var, function_obj) {
  1027. if (function_obj.parameters_list) {
  1028. for (var i = 0; i < function_obj.parameters_list.length; i++) {
  1029. if (function_obj.parameters_list[i].name == name_var) {
  1030. return true;
  1031. }
  1032. }
  1033. }
  1034. if (function_obj.variables_list) {
  1035. for (var i = 0; i < function_obj.variables_list.length; i++) {
  1036. if (function_obj.variables_list[i].name == name_var) {
  1037. return true;
  1038. }
  1039. }
  1040. }
  1041. return false;
  1042. }
  1043. function updateFunctionName (function_var, new_name, function_obj_dom) {
  1044. if (function_var.name == new_name) {
  1045. return;
  1046. }
  1047. if (isValidIdentifier(new_name)) {
  1048. if (functionNameAlreadyExists(new_name)) {
  1049. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getError('inform_valid_function_duplicated', [new_name]));
  1050. } else {
  1051. registerUserEvent(function_var.name, ActionTypes.RENAME_FUNCTION, new_name);
  1052. function_var.name = new_name;
  1053. }
  1054. } else {
  1055. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getError('inform_valid_identifier'));
  1056. }
  1057. }
  1058. function functionNameAlreadyExists (function_name) {
  1059. for (var i = 0; i < window.program_obj.functions.length; i++) {
  1060. if (window.program_obj.functions[i].name == function_name) {
  1061. return true;
  1062. }
  1063. }
  1064. return false;
  1065. }
  1066. var opened_name_parameter = false;
  1067. var opened_input_parameter = null;
  1068. function enableNameParameterUpdate (parameter_obj, parent_node, function_obj) {
  1069. if (opened_name_parameter) {
  1070. opened_input_parameter.focus();
  1071. return;
  1072. }
  1073. opened_name_parameter = true;
  1074. parent_node = $(parent_node);
  1075. var input_field;
  1076. parent_node.find('.span_name_parameter').text('');
  1077. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+parameter_obj.name+"' />" );
  1078. input_field.insertBefore(parent_node.find('.span_name_parameter'));
  1079. input_field.on('input', function() {
  1080. var inputWidth = input_field.textWidth()+10;
  1081. opened_input_parameter = input_field;
  1082. input_field.focus();
  1083. var tmpStr = input_field.val();
  1084. input_field.val('');
  1085. input_field.val(tmpStr);
  1086. input_field.css({
  1087. width: inputWidth
  1088. })
  1089. }).trigger('input');
  1090. input_field.focusout(function() {
  1091. /// update array:
  1092. if (input_field.val().trim()) {
  1093. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1094. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1095. }
  1096. input_field.off();
  1097. input_field.remove();
  1098. /// update elements:
  1099. opened_name_parameter = false;
  1100. opened_input_parameter = false;
  1101. });
  1102. input_field.on('keydown', function(e) {
  1103. var code = e.keyCode || e.which;
  1104. if(code == 13) {
  1105. if (input_field.val().trim()) {
  1106. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1107. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1108. }
  1109. input_field.off();
  1110. input_field.remove();
  1111. /// update elements:
  1112. opened_name_parameter = false;
  1113. opened_input_parameter = false;
  1114. }
  1115. if(code == 27) {
  1116. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1117. input_field.off();
  1118. input_field.remove();
  1119. /// update elements:
  1120. opened_name_parameter = false;
  1121. opened_input_parameter = false;
  1122. }
  1123. });
  1124. input_field.select();
  1125. }
  1126. var opened_name_function = false;
  1127. var opened_input = null;
  1128. var previousPadding = null;
  1129. function enableNameFunctionUpdate (function_obj, parent_node) {
  1130. if (opened_name_function) {
  1131. opened_input.focus();
  1132. return;
  1133. }
  1134. parent_node = $(parent_node);
  1135. parent_node.find('.span_name_function').text('');
  1136. var input_field;
  1137. if (!previousPadding) {
  1138. previousPadding = parent_node.find('.span_name_function').css('padding-left');
  1139. }
  1140. parent_node.find('.span_name_function').css('padding-left', '0');
  1141. parent_node.find('.span_name_function').css('padding-right', '0');
  1142. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+function_obj.name+"' />" );
  1143. input_field.insertBefore(parent_node.find('.span_name_function'));
  1144. input_field.on('input', function() {
  1145. var inputWidth = input_field.textWidth()+10;
  1146. opened_input = input_field;
  1147. input_field.focus();
  1148. var tmpStr = input_field.val();
  1149. input_field.val('');
  1150. input_field.val(tmpStr);
  1151. input_field.css({
  1152. width: inputWidth
  1153. })
  1154. }).trigger('input');
  1155. input_field.focusout(function() {
  1156. /// update array:
  1157. if (input_field.val().trim()) {
  1158. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1159. }
  1160. input_field.off();
  1161. input_field.remove();
  1162. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1163. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1164. parent_node.find('.span_name_function').text(function_obj.name);
  1165. /// update elements:
  1166. opened_name_function = false;
  1167. opened_input = false;
  1168. });
  1169. input_field.on('keydown', function(e) {
  1170. var code = e.keyCode || e.which;
  1171. if(code == 13) {
  1172. if (input_field.val().trim()) {
  1173. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1174. }
  1175. input_field.off();
  1176. input_field.remove();
  1177. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1178. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1179. parent_node.find('.span_name_function').text(function_obj.name);
  1180. /// update elements:
  1181. opened_name_function = false;
  1182. opened_input = false;
  1183. }
  1184. if(code == 27) {
  1185. input_field.off();
  1186. input_field.remove();
  1187. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1188. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1189. parent_node.find('.span_name_function').text(function_obj.name);
  1190. /// update elements:
  1191. opened_name_function = false;
  1192. opened_input = false;
  1193. }
  1194. });
  1195. input_field.select();
  1196. }
  1197. export function addFunctionChangeListener (callback) {
  1198. functionsChangeListeners.push(callback);
  1199. return functionsChangeListeners.length - 1;
  1200. }
  1201. export function addGlobalChangeListener (callback) {
  1202. globalChangeListeners.push(callback);
  1203. return globalChangeListeners.length - 1;
  1204. }
  1205. export function removeGlobalListener (index) {
  1206. globalChangeListeners.splice(index, 1);
  1207. }
  1208. export function removeFunctionListener (index) {
  1209. functionsChangeListeners.splice(index);
  1210. }
  1211. function scheduleCall (callback, time) {
  1212. const scheduled_call = () => {
  1213. const id = setInterval(() => {
  1214. if(callback()) {
  1215. clearInterval(id);
  1216. }
  1217. }, time)
  1218. }
  1219. scheduled_call();
  1220. }
  1221. function showRunButton () {
  1222. document.getElementById('run_button').style.display = 'inline';
  1223. document.getElementById('stop_button').style.display = 'none';
  1224. }
  1225. function showStopButton () {
  1226. document.getElementById('run_button').style.display = 'none';
  1227. document.getElementById('stop_button').style.display = 'inline';
  1228. }
  1229. function stopExecution () {
  1230. domConsole.clearPendingWrites();
  1231. domConsole.cancelPendingInputRequests();
  1232. if(!isRunning) {
  1233. return;
  1234. }
  1235. proc.mode = Modes.ABORT;
  1236. }