functions.js 51 KB

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