functions.js 48 KB

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