functions.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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. if (function_obj.commands.length > 0) {
  338. var teste = '.ui.sticky.sticky_cont_'+cont;
  339. $(teste).sticky({
  340. context: '.ui.bottom.attached.segment.commands_list_div.commands_cont_'+cont,
  341. scrollContext: '.ivprog_visual_panel',
  342. observeChanges: true,
  343. offset: 40,
  344. onStick: function (evt) {
  345. $(teste).css('top', '20px', 'important');
  346. },
  347. onBottom: function (evt) {
  348. $(teste).css('top', '20px', 'important');
  349. },
  350. onUnstick: function (evt) {
  351. $(teste).css('top', '20px', 'important');
  352. },
  353. onReposition: function (evt) {
  354. $(teste).css('top', '20px', 'important');
  355. },
  356. onScroll: function (evt) {
  357. $(teste).css('top', '20px', 'important');
  358. if (!isVisible($(teste), $(teste).parent())) {
  359. $(teste).removeClass('fixed');
  360. }
  361. },
  362. onTop: function (evt) {
  363. $(teste).css('top', '20px', 'important');
  364. }
  365. });
  366. }
  367. cont ++;
  368. return appender;
  369. }
  370. function isVisible (element, container) {
  371. var elementTop = $(element).offset().top,
  372. elementHeight = $(element).height(),
  373. containerTop = $(container).offset().top,
  374. containerHeight = $(container).height() - 30;
  375. return ((((elementTop - containerTop) + elementHeight) > 0)
  376. && ((elementTop - containerTop) < containerHeight));
  377. }
  378. window.evento_drag;
  379. function updateProgramObjDrag () {
  380. const nodes = Array.prototype.slice.call( $('.all_functions').children() );
  381. let function_index;
  382. // var start_index;
  383. let function_obj;
  384. $(evento_drag.item).parentsUntil(".all_functions").each(function (index) {
  385. const ref = $(this);
  386. if (ref.hasClass('function_div')) {
  387. function_index = nodes.indexOf(this);
  388. start_index = index;
  389. function_obj = ref;
  390. }
  391. });
  392. console.log(function_index);
  393. const path_target = [];
  394. $(evento_drag.item).parentsUntil(".all_functions").each(function () {
  395. if ($(this).hasClass('command_container')) {
  396. path_target.push(this);
  397. }
  398. });
  399. if (path_target.length == 0) {
  400. //console.log('soltou na raiz, na posição: ' + evento_drag.newIndex + ' mas ainda não sei de onde saiu ');
  401. } else {
  402. //console.log('soltou dentro de algum bloco, sequência vem logo abaixo (de baixo pra cima): ');
  403. //console.log(path_target);
  404. }
  405. var index_each = [];
  406. var path_relative = [];
  407. for (var i = path_target.length - 1; i >= 0; i --) {
  408. console.log('da vez', $(path_target[i + 1]));
  409. if (i == (path_target.length - 1)) { // está na raiz
  410. var indice_na_raiz = function_obj.find('.command_container').index(path_target[i]);
  411. console.log('índice na raiz: ', indice_na_raiz);
  412. } else {
  413. if ($(path_target[i + 1]).hasClass('iftrue')) {
  414. if ($(path_target[i]).parent().hasClass('commands_if')) {
  415. path_relative.push('if');
  416. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  417. } else {
  418. path_relative.push('else');
  419. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  420. }
  421. } else if ($(path_target[i + 1]).hasClass('dowhiletrue')) {
  422. path_relative.push('dowhiletrue');
  423. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  424. } else if ($(path_target[i + 1]).hasClass('repeatNtimes')) {
  425. path_relative.push('repeatNtimes');
  426. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  427. } else if ($(path_target[i + 1]).hasClass('whiletrue')) {
  428. path_relative.push('whiletrue');
  429. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  430. } else if ($(path_target[i + 1]).hasClass('switch')) {
  431. path_relative.push('switch');
  432. //index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  433. }
  434. }
  435. }
  436. // var index_in_block = -1;
  437. const is_in_else = $(evento_drag.item).parent().hasClass('commands_else');
  438. // index_in_block = $(evento_drag.item).parent().find('.command_container').index(evento_drag.item);
  439. const is_in_case_switch = $(evento_drag.item).parent().hasClass('case_commands_block');
  440. // var index_case_of_switch = -1;
  441. // if (is_in_case_switch) {
  442. // index_case_of_switch = $(evento_drag.item).parent().parent().parent().find('.case_div').index($(evento_drag.item).parent().parent());
  443. // }
  444. /*console.log('path_relative:');
  445. console.log(path_relative);
  446. console.log('index_each:');
  447. console.log(index_each);
  448. console.log('index_in_block:');
  449. console.log(index_in_block);
  450. console.log('ele está em algum bloco de senão? ');
  451. console.log(is_in_else);
  452. console.log('ele está dentro de um case de switch?');
  453. console.log(is_in_case_switch);
  454. console.log('qual é o índice do case: ');
  455. console.log(index_case_of_switch);*/
  456. // encontrar o elemento na árvore:
  457. var command_start_point = window.program_obj.functions[function_index].commands[indice_na_raiz];
  458. var block_to_insert = command_start_point;
  459. for (var i = 0; i < index_each.length; i++) {
  460. if (path_relative[i] == "else") {
  461. block_to_insert = block_to_insert.commands_else[index_each[i]];
  462. } else if (path_relative[i] == "switch") {
  463. } else {
  464. block_to_insert = block_to_insert.commands_block[index_each[i]]
  465. }
  466. }
  467. //console.log('command_start_point', command_start_point);
  468. //console.log('block_to_insert', block_to_insert);
  469. // agora tem que alocar o comando na árvore, mas considerar as quatro situações:
  470. // (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.
  471. if (path_target.length == 0) { // soltou na raiz:
  472. window.program_obj.functions[function_index].commands.splice(evento_drag.newIndex, 0, command_in_drag);
  473. } else if (is_in_else) {
  474. if (block_to_insert.commands_else) {
  475. block_to_insert.commands_else.splice(evento_drag.newIndex, 0, command_in_drag);
  476. } else {
  477. block_to_insert.commands_else = [];
  478. block_to_insert.commands_else.push(command_in_drag);
  479. }
  480. } else if (is_in_case_switch) {
  481. } else {
  482. // verificar se tem alguma coisa no bloco:
  483. if (block_to_insert.commands_block) {
  484. block_to_insert.commands_block.splice(evento_drag.newIndex, 0, command_in_drag);
  485. } else {
  486. block_to_insert.commands_block = [];
  487. block_to_insert.commands_block.push(command_in_drag);
  488. }
  489. }
  490. window.draging = false;
  491. renderAlgorithm();
  492. }
  493. function prepareDragHandler (evt) {
  494. window.draging = true;
  495. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  496. var function_index;
  497. var function_obj;
  498. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  499. if ($(this).hasClass('function_div')) {
  500. function_index = nodes.indexOf(this);
  501. function_obj = window.program_obj.functions[function_index];
  502. }
  503. });
  504. command_in_drag = $(evt.item).data("command");
  505. //console.log('$(evt.item).parent(): ');
  506. //console.log($(evt.item).parent());
  507. // descobrir qual das quatro situações:
  508. if ($(evt.item).parent().hasClass('commands_list_div')) { // está na raiz:
  509. if (function_obj.commands.indexOf(command_in_drag) > -1) {
  510. function_obj.commands.splice(function_obj.commands.indexOf(command_in_drag), 1);
  511. }
  512. } else if ($(evt.item).parent().hasClass('commands_else')) { // está no else:
  513. if ($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag) > -1) {
  514. $(evt.item).parent().data('command').commands_else.splice($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag), 1);
  515. }
  516. } else if ($(evt.item).parent().hasClass('case_commands_block')) { // está em um switch:
  517. } else { // caso padrão:
  518. if ($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag) > -1) {
  519. $(evt.item).parent().data('command').commands_block.splice($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag), 1);
  520. }
  521. }
  522. }
  523. var command_in_drag;
  524. function addSortableHandler (element, id_function) {
  525. if(true) { // DISABLE COMMAND DRAG
  526. return;
  527. }
  528. var n_group = 'commands_drag_' + id_function;
  529. Sortable.create(element, {
  530. handle: '.command_drag',
  531. ghostClass: 'ghost',
  532. animation: 300,
  533. group: {name: n_group},
  534. onEnd: function (evt) {
  535. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  536. var function_index;
  537. var function_obj;
  538. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  539. if ($(this).hasClass('function_div')) {
  540. function_index = nodes.indexOf(this);
  541. function_obj = window.program_obj.functions[function_index];
  542. }
  543. });
  544. registerUserEvent(function_obj.name, ActionTypes.MOVE_COMMAND, $(evt.item).data('command').type, '/', 'from: ' + evt.oldIndex + ' to: ' + evt.newIndex);
  545. //updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  546. var itemEl = evt.item; // dragged HTMLElement
  547. evt.to; // target list
  548. evt.from; // previous list
  549. evt.oldIndex; // element's old index within old parent
  550. evt.newIndex; // element's new index within new parent
  551. //console.log('::EVT::');
  552. //console.log(evt);
  553. window.evento_drag = evt;
  554. try {
  555. updateProgramObjDrag();
  556. } catch (e) {
  557. window.draging = false;
  558. }
  559. },
  560. onStart: function (evt) {
  561. //console.log("START::EVT::");
  562. //console.log(evt);
  563. //console.log("\n\ncommand_in_drag");
  564. try {
  565. prepareDragHandler(evt);
  566. } catch (e) {
  567. window.draging = false;
  568. }
  569. }
  570. });
  571. element = $(element);
  572. element.find(".iftrue").each(function( index ) {
  573. addSortableHandler($(this).find(".block_commands")[0], id_function);
  574. addSortableHandler($(this).find(".block_commands")[1], id_function);
  575. });
  576. element.find(".repeatNtimes").each(function( index ) {
  577. addSortableHandler($(this).find(".block_commands")[0], id_function);
  578. });
  579. element.find(".dowhiletrue").each(function( index ) {
  580. addSortableHandler($(this).find(".block_commands")[0], id_function);
  581. });
  582. element.find(".whiletrue").each(function( index ) {
  583. addSortableHandler($(this).find(".block_commands")[0], id_function);
  584. });
  585. element.find(".switch").each(function( index ) {
  586. $(this).find(".case_div").each(function( index ) {
  587. addSortableHandler($(this).find(".case_commands_block")[0], id_function);
  588. });
  589. });
  590. }
  591. export function initVisualUI () {
  592. // MUST USE CONST, LET, OR VAR !!!!!!
  593. // const mainDiv = $('#visual-main-div');
  594. // fill mainDiv with functions and globals...
  595. // renderAlgorithm()...
  596. $('.add_function_button').on('click', () => {
  597. addFunctionHandler();
  598. });
  599. $('.add_global_button').on('click', () => {
  600. window.insertContext = true;
  601. GlobalsManagement.addGlobal(program, true);
  602. });
  603. $('.run_button').on('click', () => {
  604. runCode();
  605. });
  606. $('.visual_coding_button').on('click', () => {
  607. toggleVisualCoding();
  608. });
  609. $('.textual_coding_button').on('click', () => {
  610. toggleTextualCoding();
  611. });
  612. $('.assessment').on('click', () => {
  613. runCodeAssessment();
  614. is_iassign = true;
  615. });
  616. $('.div_toggle_console').on('click', () => {
  617. toggleConsole();
  618. });
  619. $('.expand_button').on('click', () => {
  620. full_screen();
  621. });
  622. $('.help_button').on('click', () => {
  623. window.open('https://www.usp.br/line/ivprog/', '_blank');
  624. });
  625. $('.main_title h2').prop('title', LocalizedStrings.getUI('text_ivprog_description'));
  626. var time_show = 750;
  627. $('.visual_coding_button').popup({
  628. content : LocalizedStrings.getUI("tooltip_visual"),
  629. delay: {
  630. show: time_show,
  631. hide: 0
  632. }
  633. });
  634. $('.textual_coding_button').popup({
  635. content : LocalizedStrings.getUI("tooltip_textual"),
  636. delay: {
  637. show: time_show,
  638. hide: 0
  639. }
  640. });
  641. $('.upload_file_button').popup({
  642. content : LocalizedStrings.getUI("tooltip_upload"),
  643. delay: {
  644. show: time_show,
  645. hide: 0
  646. }
  647. });
  648. $('.download_file_button').popup({
  649. content : LocalizedStrings.getUI("tooltip_download"),
  650. delay: {
  651. show: time_show,
  652. hide: 0
  653. }
  654. });
  655. $('.undo_button').popup({
  656. content : LocalizedStrings.getUI("tooltip_undo"),
  657. delay: {
  658. show: time_show,
  659. hide: 0
  660. }
  661. });
  662. $('.redo_button').popup({
  663. content : LocalizedStrings.getUI("tooltip_redo"),
  664. delay: {
  665. show: time_show,
  666. hide: 0
  667. }
  668. });
  669. $('.run_button').popup({
  670. content : LocalizedStrings.getUI("tooltip_run"),
  671. delay: {
  672. show: time_show,
  673. hide: 0
  674. }
  675. });
  676. $('.assessment_button').popup({
  677. content : LocalizedStrings.getUI("tooltip_evaluate"),
  678. delay: {
  679. show: time_show,
  680. hide: 0
  681. }
  682. });
  683. $('.help_button').popup({
  684. content : LocalizedStrings.getUI("tooltip_help") + ' - ' + LocalizedStrings.getUI("text_ivprog_version") + ' ' + ivprog_version,
  685. delay: {
  686. show: time_show,
  687. hide: 0
  688. }
  689. });
  690. $('.add_global_button').popup({
  691. content : LocalizedStrings.getUI("tooltip_add_global"),
  692. delay: {
  693. show: time_show,
  694. hide: 0
  695. }
  696. });
  697. $('.div_toggle_console').popup({
  698. content : LocalizedStrings.getUI("tooltip_console"),
  699. delay: {
  700. show: time_show,
  701. hide: 0
  702. }
  703. });
  704. Sortable.create(listWithHandle, {
  705. handle: '.glyphicon-move',
  706. animation: 100,
  707. ghostClass: 'ghost',
  708. group: 'functions_divs_drag',
  709. onEnd: function (evt) {
  710. updateSequenceFunction(evt.oldIndex, evt.newIndex);
  711. }
  712. });
  713. var listGlobalsHandle = document.getElementById("listGlobalsHandle");
  714. Sortable.create(listGlobalsHandle, {
  715. handle: '.ellipsis',
  716. animation: 100,
  717. ghostClass: 'ghost',
  718. group: 'globals_divs_drag',
  719. onEnd: function (evt) {
  720. updateSequenceGlobals(evt.oldIndex, evt.newIndex);
  721. }
  722. });
  723. }
  724. export function setTestCases (testCases) {
  725. _testCases = testCases;
  726. }
  727. export function getTestCases () {
  728. // Deep clone of test cases to avoid unauthorized modification
  729. // TODO: It may be not possible to use this once custom test are fully implemented
  730. return JSON.parse(JSON.stringify(_testCases));
  731. }
  732. var is_iassign = false;
  733. function updateSequenceParameters (oldIndex, newIndex, function_obj) {
  734. function_obj.parameters_list.splice(newIndex, 0, function_obj.parameters_list.splice(oldIndex, 1)[0]);
  735. }
  736. function updateSequenceLocals (oldIndex, newIndex, function_obj) {
  737. function_obj.variables_list.splice(newIndex, 0, function_obj.variables_list.splice(oldIndex, 1)[0]);
  738. }
  739. function updateSequenceGlobals (oldIndex, newIndex) {
  740. program_obj.globals.splice(newIndex, 0, program_obj.globals.splice(oldIndex, 1)[0]);
  741. }
  742. function updateSequenceFunction (oldIndex, newIndex) {
  743. program_obj.functions.splice(newIndex, 0, program_obj.functions.splice(oldIndex, 1)[0]);
  744. }
  745. function runCodeAssessment () {
  746. window.studentGrade = null;
  747. const strCode = CodeManagement.generate();
  748. if (strCode == null) {
  749. return;
  750. }
  751. toggleConsole(true);
  752. if(domConsole == null)
  753. domConsole = new DOMConsole("#ivprog-term");
  754. $("#ivprog-term").slideDown(500);
  755. const runner = new IVProgAssessment(strCode, _testCases, domConsole);
  756. runner.runTest().then(grade => {
  757. if (!is_iassign) {
  758. parent.getEvaluationCallback(grade);
  759. } else {
  760. is_iassign = false;
  761. }
  762. }).catch( err => console.log(err));
  763. }
  764. function runCode () {
  765. const strCode = CodeManagement.generate();
  766. if (strCode == null) {
  767. return;
  768. }
  769. toggleConsole(true);
  770. if(domConsole == null)
  771. domConsole = new DOMConsole("#ivprog-term");
  772. $("#ivprog-term").slideDown(500);
  773. try {
  774. const data = SemanticAnalyser.analyseFromSource(strCode);
  775. const proc = new IVProgProcessor(data);
  776. proc.registerInput(domConsole);
  777. proc.registerOutput(domConsole);
  778. $("#ivprog-term").addClass('ivprog-term-active');
  779. proc.interpretAST().then( _ => {
  780. domConsole.info("Programa executado com sucesso!");
  781. $("#ivprog-term").removeClass('ivprog-term-active');
  782. }).catch(err => {
  783. domConsole.err(err.message);
  784. $("#ivprog-term").removeClass('ivprog-term-active');
  785. })
  786. } catch (error) {
  787. domConsole.err(error.message);
  788. console.log(error);
  789. }
  790. }
  791. function toggleConsole (is_running) {
  792. if (is_running) {
  793. $('.ivprog-term-div').css('display', 'block');
  794. $('#ivprog-term').css('min-height', '160px');
  795. $('#ivprog-term').css('margin-top', '-170px');
  796. return;
  797. }
  798. if ($('#ivprog-term').css('min-height') == '160px') {
  799. // esconder
  800. $('.ivprog-term-div').css('display', 'none');
  801. $('#ivprog-term').css('min-height', '0');
  802. $('#ivprog-term').css('margin-top', '-30px');
  803. $('#ivprog-term').css('padding', '5px');
  804. } else {
  805. // mostrar
  806. $('.ivprog-term-div').css('display', 'block');
  807. $('#ivprog-term').css('min-height', '160px');
  808. $('#ivprog-term').css('margin-top', '-170px');
  809. }
  810. }
  811. // function waitToCloseConsole () {
  812. // domConsole.info("Aperte qualquer tecla para fechar...");
  813. // const p = new Promise((resolve, _) => {
  814. // domConsole.requestInput(resolve, true);
  815. // });
  816. // p.then( _ => {
  817. // domConsole.dispose();
  818. // domConsole = null;
  819. // $("#ivprog-term").hide();
  820. // })
  821. // }
  822. function toggleTextualCoding () {
  823. var code = CodeManagement.generate();
  824. if (code == null) {
  825. return;
  826. }
  827. $('.ivprog_visual_panel').css('display', 'none');
  828. $('.ivprog_textual_panel').css('display', 'block');
  829. $('.ivprog_textual_panel').removeClass('loading');
  830. $('.ivprog_textual_code').text(code);
  831. $('.visual_coding_button').removeClass('active');
  832. $('.textual_coding_button').addClass('active');
  833. }
  834. function toggleVisualCoding () {
  835. $('.ivprog_textual_panel').addClass('loading');
  836. $('.ivprog_textual_panel').css('display', 'none');
  837. $('.ivprog_visual_panel').css('display', 'block');
  838. $('.textual_coding_button').removeClass('active');
  839. $('.visual_coding_button').addClass('active');
  840. }
  841. function removeParameter (function_obj, parameter_obj, parameter_container) {
  842. registerUserEvent(parameter_obj.name, ActionTypes.REMOVE_FUNCTION_PARAM, function_obj.name);
  843. var index = function_obj.parameters_list.indexOf(parameter_obj);
  844. if (index > -1) {
  845. window.insertContext = true;
  846. function_obj.parameters_list.splice(index, 1);
  847. }
  848. $(parameter_container).fadeOut();
  849. }
  850. function updateParameterType (parameter_obj, new_type, function_name, new_dimensions = 0) {
  851. registerUserEvent(parameter_obj.name, ActionTypes.CHANGE_PARAM_TYPE, function_name, new_type, new_dimensions);
  852. parameter_obj.type = new_type;
  853. parameter_obj.dimensions = new_dimensions;
  854. if (new_dimensions > 0) {
  855. parameter_obj.rows = new_dimensions;
  856. parameter_obj.columns = 2;
  857. }
  858. }
  859. function renderParameter (function_obj, parameter_obj, function_container) {
  860. let ret = "";
  861. ret += '<div class="ui label function_name_parameter pink"><i class="ui icon ellipsis vertical inverted"></i>';
  862. ret += '<div class="ui dropdown parameter_type">';
  863. if (parameter_obj.dimensions > 0) {
  864. ret += '<div class="text">'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(parameter_obj.type);
  865. if (parameter_obj.dimensions == 1) {
  866. ret += ' [ ] ';
  867. } else {
  868. ret += ' [ ] [ ] ';
  869. }
  870. ret += '</div>';
  871. } else {
  872. ret += '<div class="text">'+LocalizedStrings.getUI(parameter_obj.type)+'</div>';
  873. }
  874. ret += '<div class="menu">';
  875. for (const tm in Types) {
  876. if (tm == Types.VOID.toUpperCase()) {
  877. continue;
  878. }
  879. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(tm.toLowerCase())+'</div>';
  880. }
  881. for (const tm in Types) {
  882. if (tm == Types.VOID.toUpperCase()) {
  883. continue;
  884. }
  885. ret += '<div class="item">'
  886. + '<i class="dropdown icon"></i>'
  887. + LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())
  888. + '<div class="menu">'
  889. + '<div class="item" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())+' [ ] " data-type="'+tm+'" data-dimensions="1">[ ]</div>'
  890. + '<div class="item" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())+' [ ] [ ] " data-type="'+tm+'" data-dimensions="2">[ ] [ ] </div>'
  891. + '</div>'
  892. + '</div>';
  893. }
  894. ret += '</div></div>';
  895. ret += '<div class="parameter_div_edit"><span class="span_name_parameter label_enable_name_parameter">'+parameter_obj.name+'</span></div> ';
  896. ret += ' <i class="yellow inverted icon times remove_parameter"></i></div>';
  897. ret = $(ret);
  898. function_container.find('.container_parameters_list').append(ret);
  899. ret.find('.remove_parameter').on('click', function(e){
  900. removeParameter(function_obj, parameter_obj, ret);
  901. });
  902. ret.find('.ui.dropdown.parameter_type').dropdown({
  903. onChange: function(_, __, $selectedItem) {
  904. if ($selectedItem.data('dimensions')) {
  905. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name, $selectedItem.data('dimensions'));
  906. } else {
  907. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name);
  908. }
  909. },
  910. selectOnKeydown: false
  911. });
  912. ret.find('.label_enable_name_parameter').on('click', function(e){
  913. registerUserEvent(function_obj.name, ActionTypes.ENTER_CHANGE_PARAM_NAME, parameter_obj.name);
  914. enableNameParameterUpdate(parameter_obj, ret, function_obj);
  915. });
  916. return ret;
  917. }
  918. function updateParameterName (parameter_var, new_name, parameter_obj_dom, function_obj) {
  919. if (parameter_var.name == new_name) {
  920. return;
  921. }
  922. if (isValidIdentifier(new_name)) {
  923. if (variableNameAlreadyExists(new_name, function_obj)) {
  924. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getUI('inform_valid_variable_duplicated'));
  925. } else {
  926. registerUserEvent(parameter_var.name, ActionTypes.RENAME_FUNCTION_PARAM, function_obj.name, new_name);
  927. parameter_var.name = new_name;
  928. }
  929. } else {
  930. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getUI('inform_valid_name'));
  931. }
  932. }
  933. function variableNameAlreadyExists (name_var, function_obj) {
  934. if (function_obj.parameters_list) {
  935. for (var i = 0; i < function_obj.parameters_list.length; i++) {
  936. if (function_obj.parameters_list[i].name == name_var) {
  937. return true;
  938. }
  939. }
  940. }
  941. if (function_obj.variables_list) {
  942. for (var i = 0; i < function_obj.variables_list.length; i++) {
  943. if (function_obj.variables_list[i].name == name_var) {
  944. return true;
  945. }
  946. }
  947. }
  948. return false;
  949. }
  950. function updateFunctionName (function_var, new_name, function_obj_dom) {
  951. if (function_var.name == new_name) {
  952. return;
  953. }
  954. if (isValidIdentifier(new_name)) {
  955. if (functionNameAlreadyExists(new_name)) {
  956. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getUI('inform_valid_name_duplicated'));
  957. } else {
  958. registerUserEvent(function_var.name, ActionTypes.RENAME_FUNCTION, new_name);
  959. function_var.name = new_name;
  960. }
  961. } else {
  962. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getUI('inform_valid_name'));
  963. }
  964. }
  965. function functionNameAlreadyExists (function_name) {
  966. for (var i = 0; i < window.program_obj.functions.length; i++) {
  967. if (window.program_obj.functions[i].name == function_name) {
  968. return true;
  969. }
  970. }
  971. return false;
  972. }
  973. function isValidIdentifier (identifier_str) {
  974. return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier_str);
  975. }
  976. var opened_name_parameter = false;
  977. var opened_input_parameter = null;
  978. function enableNameParameterUpdate (parameter_obj, parent_node, function_obj) {
  979. if (opened_name_parameter) {
  980. opened_input_parameter.focus();
  981. return;
  982. }
  983. opened_name_parameter = true;
  984. parent_node = $(parent_node);
  985. var input_field;
  986. parent_node.find('.span_name_parameter').text('');
  987. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+parameter_obj.name+"' />" );
  988. input_field.insertBefore(parent_node.find('.span_name_parameter'));
  989. input_field.on('input', function() {
  990. var inputWidth = input_field.textWidth()+10;
  991. opened_input_parameter = input_field;
  992. input_field.focus();
  993. var tmpStr = input_field.val();
  994. input_field.val('');
  995. input_field.val(tmpStr);
  996. input_field.css({
  997. width: inputWidth
  998. })
  999. }).trigger('input');
  1000. input_field.focusout(function() {
  1001. /// update array:
  1002. if (input_field.val().trim()) {
  1003. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1004. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1005. }
  1006. input_field.off();
  1007. input_field.remove();
  1008. /// update elements:
  1009. opened_name_parameter = false;
  1010. opened_input_parameter = false;
  1011. });
  1012. input_field.on('keydown', function(e) {
  1013. var code = e.keyCode || e.which;
  1014. if(code == 13) {
  1015. if (input_field.val().trim()) {
  1016. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1017. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1018. }
  1019. input_field.off();
  1020. input_field.remove();
  1021. /// update elements:
  1022. opened_name_parameter = false;
  1023. opened_input_parameter = false;
  1024. }
  1025. if(code == 27) {
  1026. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1027. input_field.off();
  1028. input_field.remove();
  1029. /// update elements:
  1030. opened_name_parameter = false;
  1031. opened_input_parameter = false;
  1032. }
  1033. });
  1034. input_field.select();
  1035. }
  1036. var opened_name_function = false;
  1037. var opened_input = null;
  1038. var previousPadding = null;
  1039. function enableNameFunctionUpdate (function_obj, parent_node) {
  1040. if (opened_name_function) {
  1041. opened_input.focus();
  1042. return;
  1043. }
  1044. parent_node = $(parent_node);
  1045. parent_node.find('.span_name_function').text('');
  1046. var input_field;
  1047. if (!previousPadding) {
  1048. previousPadding = parent_node.find('.span_name_function').css('padding-left');
  1049. }
  1050. parent_node.find('.span_name_function').css('padding-left', '0');
  1051. parent_node.find('.span_name_function').css('padding-right', '0');
  1052. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+function_obj.name+"' />" );
  1053. input_field.insertBefore(parent_node.find('.span_name_function'));
  1054. input_field.on('input', function() {
  1055. var inputWidth = input_field.textWidth()+10;
  1056. opened_input = input_field;
  1057. input_field.focus();
  1058. var tmpStr = input_field.val();
  1059. input_field.val('');
  1060. input_field.val(tmpStr);
  1061. input_field.css({
  1062. width: inputWidth
  1063. })
  1064. }).trigger('input');
  1065. input_field.focusout(function() {
  1066. /// update array:
  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. input_field.on('keydown', function(e) {
  1080. var code = e.keyCode || e.which;
  1081. if(code == 13) {
  1082. if (input_field.val().trim()) {
  1083. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1084. }
  1085. input_field.off();
  1086. input_field.remove();
  1087. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1088. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1089. parent_node.find('.span_name_function').text(function_obj.name);
  1090. /// update elements:
  1091. opened_name_function = false;
  1092. opened_input = false;
  1093. }
  1094. if(code == 27) {
  1095. input_field.off();
  1096. input_field.remove();
  1097. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1098. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1099. parent_node.find('.span_name_function').text(function_obj.name);
  1100. /// update elements:
  1101. opened_name_function = false;
  1102. opened_input = false;
  1103. }
  1104. });
  1105. input_field.select();
  1106. }
  1107. export function addFunctionChangeListener (callback) {
  1108. functionsChangeListeners.push(callback);
  1109. return functionsChangeListeners.length - 1;
  1110. }
  1111. export function addGlobalChangeListener (callback) {
  1112. globalChangeListeners.push(callback);
  1113. return globalChangeListeners.length - 1;
  1114. }
  1115. export function removeGlobalListener (index) {
  1116. globalChangeListeners.splice(index, 1);
  1117. }
  1118. export function removeFunctionListener (index) {
  1119. functionsChangeListeners.splice(index);
  1120. }