functions.js 46 KB

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