functions.js 48 KB

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