functions.js 50 KB

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