functions.js 48 KB

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