functions.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. import { Types } from './types';
  2. import * as Models from './ivprog_elements';
  3. import { LocalizedStrings } from './../services/localizedStringsService';
  4. import * as GlobalsManagement from './globals';
  5. import * as VariablesManagement from './variables';
  6. import * as CommandsManagement from './commands';
  7. import * as CodeManagement from './code_generator';
  8. import * as VariableValueMenu from './commands/variable_value_menu';
  9. import { DOMConsole } from './../io/domConsole';
  10. import { IVProgProcessor } from './../processor/ivprogProcessor';
  11. import WatchJS from 'melanke-watchjs';
  12. import { SemanticAnalyser } from '../processor/semantic/semanticAnalyser';
  13. import { IVProgAssessment } from '../assessment/ivprogAssessment';
  14. import * as AlgorithmManagement from './algorithm';
  15. import * as Utils from './utils';
  16. import VersionInfo from './../../.ima_version.json';
  17. var counter_new_functions = 0;
  18. var counter_new_parameters = 0;
  19. var ivprog_version = VersionInfo.version;
  20. const globalChangeListeners = [];
  21. const functionsChangeListeners = [];
  22. let domConsole = null;
  23. let _testCases = [];
  24. window.studentGrade = null;
  25. window.LocalizedStrings = LocalizedStrings;
  26. const program = new Models.Program();
  27. window.system_functions = [];
  28. // Adding math functions:
  29. window.system_functions.push(new Models.SystemFunction('$sin', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  30. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  31. window.system_functions.push(new Models.SystemFunction('$cos', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  32. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  33. window.system_functions.push(new Models.SystemFunction('$tan', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  34. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  35. window.system_functions.push(new Models.SystemFunction('$sqrt', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  36. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  37. window.system_functions.push(new Models.SystemFunction('$pow', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  38. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  39. window.system_functions.push(new Models.SystemFunction('$log', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  40. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  41. window.system_functions.push(new Models.SystemFunction('$abs', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  42. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  43. window.system_functions.push(new Models.SystemFunction('$negate', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  44. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  45. window.system_functions.push(new Models.SystemFunction('$invert', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  46. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  47. window.system_functions.push(new Models.SystemFunction('$max', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  48. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  49. window.system_functions.push(new Models.SystemFunction('$min', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  50. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  51. // Adding text functions:
  52. window.system_functions.push(new Models.SystemFunction('$substring', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true),
  53. new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true),new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  54. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  55. window.system_functions.push(new Models.SystemFunction('$length', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  56. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  57. window.system_functions.push(new Models.SystemFunction('$uppercase', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  58. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  59. window.system_functions.push(new Models.SystemFunction('$lowercase', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  60. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  61. window.system_functions.push(new Models.SystemFunction('$charAt', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  62. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  63. // Adding arrangement functions:
  64. window.system_functions.push(new Models.SystemFunction('$numElements', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 1)],
  65. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  66. window.system_functions.push(new Models.SystemFunction('$matrixLines', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 2)],
  67. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  68. window.system_functions.push(new Models.SystemFunction('$matrixColumns', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.variable_and_function, null, null, null, true, 2)],
  69. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  70. // Adding conversion functions:
  71. window.system_functions.push(new Models.SystemFunction('$isReal', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  72. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  73. window.system_functions.push(new Models.SystemFunction('$isInt', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  74. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  75. window.system_functions.push(new Models.SystemFunction('$isBool', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  76. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  77. window.system_functions.push(new Models.SystemFunction('$castReal', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  78. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  79. window.system_functions.push(new Models.SystemFunction('$castInt', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  80. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  81. window.system_functions.push(new Models.SystemFunction('$castBool', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  82. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  83. window.system_functions.push(new Models.SystemFunction('$castString', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  84. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  85. console.log(' ___ ___ ________ \n / / / / / ____/ \n / / / / / / \n / / / / ______ ___ / /__ \n / / / / / \\ / / / ___/ \n / /______ / / / /\\ \\/ / / / \n / / / / / / \\ / / /____ \n/__________/ /___/ /___/ \\___/ /________/ \n\n Laboratório de Informática na Educação\n http://line.ime.usp.br');
  86. const mainFunction = new Models.Function(LocalizedStrings.getUI("start"), Types.VOID, 0, [], true, false);
  87. mainFunction.function_comment = new Models.Comment(LocalizedStrings.getUI('text_comment_main'));
  88. program.addFunction(mainFunction);
  89. window.program_obj = program;
  90. window.generator = CodeManagement.generate;
  91. window.runCodeAssessment = runCodeAssessment;
  92. window.renderAlgorithm = AlgorithmManagement.renderAlgorithm;
  93. window.insertContext = false;
  94. window.watchW = WatchJS;
  95. WatchJS.watch(window.program_obj.globals, function(){
  96. if (window.insertContext) {
  97. setTimeout(function() {
  98. AlgorithmManagement.renderAlgorithm();
  99. globalChangeListeners.forEach(x => x());
  100. }, 300);
  101. window.insertContext = false;
  102. } else {
  103. AlgorithmManagement.renderAlgorithm();
  104. globalChangeListeners.forEach(x => x());
  105. }
  106. }, 1);
  107. WatchJS.watch(window.program_obj.functions, function(){
  108. if (window.insertContext) {
  109. setTimeout(function(){
  110. AlgorithmManagement.renderAlgorithm();
  111. functionsChangeListeners.forEach( x => x());
  112. }, 300);
  113. window.insertContext = false;
  114. } else {
  115. AlgorithmManagement.renderAlgorithm();
  116. functionsChangeListeners.forEach( x => x());
  117. }
  118. }, 1);
  119. function addFunctionHandler () {
  120. 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')));
  121. program.addFunction(new_function);
  122. counter_new_functions ++;
  123. window.insertContext = true;
  124. var newe = renderFunction(new_function);
  125. /*newe.css('display', 'none');
  126. newe.fadeIn();*/
  127. }
  128. function addParameter (function_obj, function_container, is_from_click = false) {
  129. if (function_obj.parameters_list == null) {
  130. function_obj.parameters_list = [];
  131. }
  132. var new_parameter = new Models.Variable(Types.INTEGER, LocalizedStrings.getUI("new_parameter") + "_" + counter_new_parameters);
  133. function_obj.parameters_list.push(new_parameter);
  134. counter_new_parameters ++;
  135. var newe = renderParameter(function_obj, new_parameter, function_container);
  136. if (is_from_click) {
  137. /*newe.css('display', 'none');
  138. newe.fadeIn();*/
  139. }
  140. }
  141. function updateReturnType (function_obj, new_type, new_dimensions = 0) {
  142. function_obj.return_type = new_type;
  143. function_obj.return_dimensions = new_dimensions;
  144. }
  145. function removeFunction (function_obj) {
  146. var index = program.functions.indexOf(function_obj);
  147. if (index > -1) {
  148. program.functions.splice(index, 1);
  149. }
  150. }
  151. function minimizeFunction (function_obj) {
  152. function_obj.is_hidden = !function_obj.is_hidden;
  153. }
  154. function addHandlers (function_obj, function_container) {
  155. function_container.find('.ui.dropdown.function_return').dropdown({
  156. onChange: function(value, text, $selectedItem) {
  157. if ($selectedItem.data('dimensions')) {
  158. updateReturnType(function_obj, Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
  159. } else {
  160. updateReturnType(function_obj, Types[$selectedItem.data('type')]);
  161. }
  162. },
  163. selectOnKeydown: false
  164. });
  165. function_container.find( ".name_function_updated" ).on('click', function(e){
  166. enableNameFunctionUpdate(function_obj, function_container);
  167. });
  168. function_container.find( ".add_parameter_button" ).on('click', function(e){
  169. window.insertContext = true;
  170. addParameter(function_obj, function_container, true);
  171. });
  172. function_container.find('.menu_commands').dropdown({
  173. on: 'hover'
  174. });
  175. function_container.find('.menu_commands a').on('click', function(evt){
  176. if (function_obj.commands == null || function_obj.commands.length == 0) {
  177. function_obj.commands = [];
  178. var new_cmd = CommandsManagement.genericCreateCommand($(this).data('command'));
  179. function_obj.commands.push(new_cmd);
  180. CommandsManagement.renderCommand(new_cmd, function_container.find('.commands_list_div'), 3, function_obj);
  181. } else {
  182. CommandsManagement.createFloatingCommand(function_obj, function_container, $(this).data('command'), evt);
  183. }
  184. });
  185. function_container.find('.add_var_button_function').on('click', function(e){
  186. window.insertContext = true;
  187. VariablesManagement.addVariable(function_obj, function_container, true);
  188. });
  189. function_container.find('.remove_function_button').on('click', function(e){
  190. removeFunction(function_obj);
  191. function_container.fadeOut();
  192. });
  193. function_container.find('.minimize_function_button').on('click', function(e){
  194. minimizeFunction(function_obj);
  195. if (function_obj.is_hidden) {
  196. function_container.find(".add_var_button_function").toggle();
  197. function_container.find(".inline_add_command").toggle();
  198. function_container.find(".function_area").slideToggle();
  199. } else {
  200. function_container.find(".function_area").slideToggle(function(){
  201. function_container.find(".add_var_button_function").toggle();
  202. function_container.find(".inline_add_command").toggle();
  203. });
  204. }
  205. });
  206. }
  207. // Essa função imprime o tipo de retorno da função e cria o menu do tipo 'select' para alteração
  208. function renderFunctionReturn (function_obj, function_element) {
  209. var ret = '<div class="ui dropdown function_return">';
  210. if (function_obj.return_dimensions > 0) {
  211. ret += '<div class="text">'+ LocalizedStrings.getUI("vector") +':'+ LocalizedStrings.getUI(function_obj.return_type);
  212. if (function_obj.return_dimensions == 1) {
  213. ret += ' [ ] ';
  214. } else {
  215. ret += ' [ ] [ ] ';
  216. }
  217. ret += '</div>';
  218. } else {
  219. ret += '<div class="text">'+LocalizedStrings.getUI(function_obj.return_type)+'</div>';
  220. }
  221. ret += '<div class="menu">';
  222. for (var tm in Types) {
  223. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions < 1 ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(tm.toLowerCase())+'</div>';
  224. }
  225. for (var tm in Types) {
  226. if (tm == Types.VOID.toUpperCase()) {
  227. continue;
  228. }
  229. ret += '<div class="item">'
  230. + '<i class="dropdown icon"></i>'
  231. + LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())
  232. + '<div class="menu">'
  233. + '<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>'
  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="2">[ ] [ ] </div>'
  235. + '</div>'
  236. + '</div>';
  237. }
  238. ret += '</div></div>';
  239. ret = $(ret);
  240. function_element.find('.function_return').append(ret);
  241. }
  242. var cont = 0;
  243. export function renderFunction (function_obj) {
  244. var appender = '<div class="ui secondary segment function_div list-group-item function_cont_'+cont+'">';
  245. if (function_obj.function_comment) {
  246. //appender += renderComment(function_obj.function_comment, sequence, true, -1);
  247. }
  248. appender += '<span class="glyphicon glyphicon-move move_function" aria-hidden="true"><i class="icon sort alternate vertical"></i></span>';
  249. 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>')
  250. + '<button class="ui icon button tiny minimize_function_button"><i class="icon window minimize"></i></button>';
  251. appender += '<div class="function_signature_div">'+LocalizedStrings.getUI("function")+' ';
  252. if (function_obj.is_main) {
  253. 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> '
  254. + ' <span class="parethesis_function">( </span> <div class="ui large labels parameters_list">';
  255. } else {
  256. appender += '<div class="ui function_return"></div>';
  257. appender += '<div class="function_name_div function_name_div_updated"><span class="span_name_function name_function_updated">'+function_obj.name+'</span> </div> '
  258. + ' <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">';
  259. }
  260. appender += '</div> <span class="parethesis_function"> ) </span> </div>'
  261. + (function_obj.is_hidden ? ' <div class="function_area" style="display: none;"> ' : ' <div class="function_area"> ');
  262. 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>';
  263. appender += '<div class="ui top attached segment variables_list_div"></div>';
  264. appender += '<div class="ui bottom attached segment commands_list_div commands_cont_'+cont+'">'
  265. + '<div class="ui rail" style="width: 35px; margin-left: -36px;"><div class="ui sticky sticky_cont_'+cont+'" style="top: 50px !important;">';
  266. 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"> ';
  267. appender += '<a class="item" data-command="'+Models.COMMAND_TYPES.reader+'"><i class="download icon"></i> ' +LocalizedStrings.getUI('text_read_var')+ '</a>'
  268. + '<a class="item" data-command="'+Models.COMMAND_TYPES.writer+'"><i class="upload icon"></i> '+LocalizedStrings.getUI('text_write_var')+'</a>'
  269. + '<a class="item" data-command="'+Models.COMMAND_TYPES.comment+'"><i class="quote left icon"></i> '+LocalizedStrings.getUI('text_comment')+'</a>'
  270. + '<a class="item" data-command="'+Models.COMMAND_TYPES.attribution+'"><i class="arrow left icon"></i> '+LocalizedStrings.getUI('text_attribution')+'</a>'
  271. + '<a class="item" data-command="'+Models.COMMAND_TYPES.functioncall+'"><i class="hand point right icon"></i> '+LocalizedStrings.getUI('text_functioncall')+'</a>'
  272. + '<a class="item" data-command="'+Models.COMMAND_TYPES.iftrue+'" ><i class="random icon"></i> '+LocalizedStrings.getUI('text_iftrue')+'</a>'
  273. + '<a class="item" data-command="'+Models.COMMAND_TYPES.repeatNtimes+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_repeatNtimes')+'</a>'
  274. + '<a class="item" data-command="'+Models.COMMAND_TYPES.whiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_whiletrue')+'</a>'
  275. + '<a class="item" data-command="'+Models.COMMAND_TYPES.dowhiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_dowhiletrue')+'</a>'
  276. + '<a class="item" data-command="'+Models.COMMAND_TYPES.switch+'"><i class="list icon"></i> '+LocalizedStrings.getUI('text_switch')+'</a>'
  277. + '<a class="item" data-command="'+Models.COMMAND_TYPES.return+'"><i class="reply icon"></i> '+LocalizedStrings.getUI('text_btn_return')+'</a>'
  278. + '</div></div>';
  279. appender += '</div></div>'
  280. +'</div>';
  281. appender += '</div></div>';
  282. appender = $(appender);
  283. $('.all_functions').append(appender);
  284. appender.data('fun', function_obj);
  285. appender.find('.commands_list_div').data('fun', function_obj);
  286. renderFunctionReturn(function_obj, appender);
  287. addHandlers(function_obj, appender);
  288. // Rendering parameters:
  289. for (var j = 0; j < function_obj.parameters_list.length; j++) {
  290. renderParameter(function_obj, function_obj.parameters_list[j], appender);
  291. }
  292. // Rendering variables:
  293. for (var j = 0; j < function_obj.variables_list.length; j++) {
  294. VariablesManagement.renderVariable(appender, function_obj.variables_list[j], function_obj);
  295. }
  296. // Rendering commands:
  297. for (var j = 0; j < function_obj.commands.length; j++) {
  298. CommandsManagement.renderCommand(function_obj.commands[j], $(appender.find('.commands_list_div')[0]), 3, function_obj);
  299. }
  300. $('.minimize_function_button').popup({
  301. content : LocalizedStrings.getUI("tooltip_minimize"),
  302. delay: {
  303. show: 750,
  304. hide: 0
  305. }
  306. });
  307. var function_index = program.functions.indexOf(function_obj);
  308. Sortable.create(appender.find(".variables_list_div")[0], {
  309. handle: '.ellipsis',
  310. animation: 100,
  311. ghostClass: 'ghost',
  312. group: 'local_vars_drag_' + function_index,
  313. onEnd: function (evt) {
  314. updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  315. }
  316. });
  317. addSortableHandler(appender.find(".commands_list_div")[0], function_index);
  318. if (!function_obj.is_main) {
  319. Sortable.create(appender.find(".container_parameters_list")[0], {
  320. handle: '.ellipsis',
  321. animation: 100,
  322. ghostClass: 'ghost',
  323. group: 'parameters_drag_' + program.functions.indexOf(function_obj),
  324. onEnd: function (evt) {
  325. updateSequenceParameters(evt.oldIndex, evt.newIndex, function_obj);
  326. }
  327. });
  328. }
  329. if (function_obj.commands.length > 0) {
  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. }
  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. var time_show = 750;
  605. $('.visual_coding_button').popup({
  606. content : LocalizedStrings.getUI("tooltip_visual"),
  607. delay: {
  608. show: time_show,
  609. hide: 0
  610. }
  611. });
  612. $('.textual_coding_button').popup({
  613. content : LocalizedStrings.getUI("tooltip_textual"),
  614. delay: {
  615. show: time_show,
  616. hide: 0
  617. }
  618. });
  619. $('.upload_file_button').popup({
  620. content : LocalizedStrings.getUI("tooltip_upload"),
  621. delay: {
  622. show: time_show,
  623. hide: 0
  624. }
  625. });
  626. $('.download_file_button').popup({
  627. content : LocalizedStrings.getUI("tooltip_download"),
  628. delay: {
  629. show: time_show,
  630. hide: 0
  631. }
  632. });
  633. $('.undo_button').popup({
  634. content : LocalizedStrings.getUI("tooltip_undo"),
  635. delay: {
  636. show: time_show,
  637. hide: 0
  638. }
  639. });
  640. $('.redo_button').popup({
  641. content : LocalizedStrings.getUI("tooltip_redo"),
  642. delay: {
  643. show: time_show,
  644. hide: 0
  645. }
  646. });
  647. $('.run_button').popup({
  648. content : LocalizedStrings.getUI("tooltip_run"),
  649. delay: {
  650. show: time_show,
  651. hide: 0
  652. }
  653. });
  654. $('.assessment_button').popup({
  655. content : LocalizedStrings.getUI("tooltip_evaluate"),
  656. delay: {
  657. show: time_show,
  658. hide: 0
  659. }
  660. });
  661. $('.help_button').popup({
  662. content : LocalizedStrings.getUI("tooltip_help") + ' - ' + LocalizedStrings.getUI("text_ivprog_version") + ' ' + ivprog_version,
  663. delay: {
  664. show: time_show,
  665. hide: 0
  666. }
  667. });
  668. $('.add_global_button').popup({
  669. content : LocalizedStrings.getUI("tooltip_add_global"),
  670. delay: {
  671. show: time_show,
  672. hide: 0
  673. }
  674. });
  675. $('.div_toggle_console').popup({
  676. content : LocalizedStrings.getUI("tooltip_console"),
  677. delay: {
  678. show: time_show,
  679. hide: 0
  680. }
  681. });
  682. Sortable.create(listWithHandle, {
  683. handle: '.glyphicon-move',
  684. animation: 100,
  685. ghostClass: 'ghost',
  686. group: 'functions_divs_drag',
  687. onEnd: function (evt) {
  688. updateSequenceFunction(evt.oldIndex, evt.newIndex);
  689. }
  690. });
  691. var listGlobalsHandle = document.getElementById("listGlobalsHandle");
  692. Sortable.create(listGlobalsHandle, {
  693. handle: '.ellipsis',
  694. animation: 100,
  695. ghostClass: 'ghost',
  696. group: 'globals_divs_drag',
  697. onEnd: function (evt) {
  698. updateSequenceGlobals(evt.oldIndex, evt.newIndex);
  699. }
  700. });
  701. }
  702. export function setTestCases (testCases) {
  703. _testCases = testCases;
  704. }
  705. export function getTestCases () {
  706. // Deep clone of test cases to avoid unauthorized modification
  707. // TODO: It may be not possible to use this once custom test are fully implemented
  708. return JSON.parse(JSON.stringify(_testCases));
  709. }
  710. var is_iassign = false;
  711. function updateSequenceParameters (oldIndex, newIndex, function_obj) {
  712. function_obj.parameters_list.splice(newIndex, 0, function_obj.parameters_list.splice(oldIndex, 1)[0]);
  713. }
  714. function updateSequenceLocals (oldIndex, newIndex, function_obj) {
  715. function_obj.variables_list.splice(newIndex, 0, function_obj.variables_list.splice(oldIndex, 1)[0]);
  716. }
  717. function updateSequenceGlobals (oldIndex, newIndex) {
  718. program_obj.globals.splice(newIndex, 0, program_obj.globals.splice(oldIndex, 1)[0]);
  719. }
  720. function updateSequenceFunction (oldIndex, newIndex) {
  721. program_obj.functions.splice(newIndex, 0, program_obj.functions.splice(oldIndex, 1)[0]);
  722. }
  723. function runCodeAssessment () {
  724. window.studentGrade = null;
  725. const strCode = CodeManagement.generate();
  726. if (strCode == null) {
  727. return;
  728. }
  729. toggleConsole(true);
  730. if(domConsole == null)
  731. domConsole = new DOMConsole("#ivprog-term");
  732. $("#ivprog-term").slideDown(500);
  733. const runner = new IVProgAssessment(strCode, _testCases, domConsole);
  734. runner.runTest().then(grade => {
  735. if (!is_iassign) {
  736. parent.getEvaluationCallback(grade);
  737. } else {
  738. is_iassign = false;
  739. }
  740. }).catch( err => console.log(err));
  741. }
  742. function runCode () {
  743. const strCode = CodeManagement.generate();
  744. if (strCode == null) {
  745. return;
  746. }
  747. toggleConsole(true);
  748. if(domConsole == null)
  749. domConsole = new DOMConsole("#ivprog-term");
  750. $("#ivprog-term").slideDown(500);
  751. try {
  752. const data = SemanticAnalyser.analyseFromSource(strCode);
  753. const proc = new IVProgProcessor(data);
  754. proc.registerInput(domConsole);
  755. proc.registerOutput(domConsole);
  756. $("#ivprog-term").addClass('ivprog-term-active');
  757. proc.interpretAST().then( _ => {
  758. domConsole.info("Programa executado com sucesso!");
  759. $("#ivprog-term").removeClass('ivprog-term-active');
  760. }).catch(err => {
  761. domConsole.err(err.message);
  762. $("#ivprog-term").removeClass('ivprog-term-active');
  763. })
  764. } catch (error) {
  765. domConsole.err(error.message);
  766. console.log(error);
  767. }
  768. }
  769. function toggleConsole (is_running) {
  770. if (is_running) {
  771. $('.ivprog-term-div').css('display', 'block');
  772. $('#ivprog-term').css('min-height', '160px');
  773. $('#ivprog-term').css('margin-top', '-170px');
  774. return;
  775. }
  776. if ($('#ivprog-term').css('min-height') == '160px') {
  777. // esconder
  778. $('.ivprog-term-div').css('display', 'none');
  779. $('#ivprog-term').css('min-height', '0');
  780. $('#ivprog-term').css('margin-top', '-30px');
  781. $('#ivprog-term').css('padding', '5px');
  782. } else {
  783. // mostrar
  784. $('.ivprog-term-div').css('display', 'block');
  785. $('#ivprog-term').css('min-height', '160px');
  786. $('#ivprog-term').css('margin-top', '-170px');
  787. }
  788. }
  789. function waitToCloseConsole () {
  790. domConsole.info("Aperte qualquer tecla para fechar...");
  791. const p = new Promise((resolve, _) => {
  792. domConsole.requestInput(resolve, true);
  793. });
  794. p.then( _ => {
  795. domConsole.dispose();
  796. domConsole = null;
  797. $("#ivprog-term").hide();
  798. })
  799. }
  800. function toggleTextualCoding () {
  801. var code = CodeManagement.generate();
  802. if (code == null) {
  803. return;
  804. }
  805. $('.ivprog_visual_panel').css('display', 'none');
  806. $('.ivprog_textual_panel').css('display', 'block');
  807. $('.ivprog_textual_panel').removeClass('loading');
  808. $('.ivprog_textual_code').text(code);
  809. $('.visual_coding_button').removeClass('active');
  810. $('.textual_coding_button').addClass('active');
  811. }
  812. function toggleVisualCoding () {
  813. $('.ivprog_textual_panel').addClass('loading');
  814. $('.ivprog_textual_panel').css('display', 'none');
  815. $('.ivprog_visual_panel').css('display', 'block');
  816. $('.textual_coding_button').removeClass('active');
  817. $('.visual_coding_button').addClass('active');
  818. }
  819. function removeParameter (function_obj, parameter_obj, parameter_container) {
  820. var index = function_obj.parameters_list.indexOf(parameter_obj);
  821. if (index > -1) {
  822. window.insertContext = true;
  823. function_obj.parameters_list.splice(index, 1);
  824. }
  825. $(parameter_container).fadeOut();
  826. }
  827. function updateParameterType (parameter_obj, new_type, new_dimensions = 0) {
  828. parameter_obj.type = new_type;
  829. parameter_obj.dimensions = new_dimensions;
  830. if (new_dimensions > 0) {
  831. parameter_obj.rows = new_dimensions;
  832. parameter_obj.columns = 2;
  833. }
  834. }
  835. function renderParameter (function_obj, parameter_obj, function_container) {
  836. var ret = "";
  837. ret += '<div class="ui label function_name_parameter pink"><i class="ui icon ellipsis vertical inverted"></i>';
  838. ret += '<div class="ui dropdown parameter_type">';
  839. if (parameter_obj.dimensions > 0) {
  840. ret += '<div class="text">'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(parameter_obj.type);
  841. if (parameter_obj.dimensions == 1) {
  842. ret += ' [ ] ';
  843. } else {
  844. ret += ' [ ] [ ] ';
  845. }
  846. ret += '</div>';
  847. } else {
  848. ret += '<div class="text">'+LocalizedStrings.getUI(parameter_obj.type)+'</div>';
  849. }
  850. ret += '<div class="menu">';
  851. for (var tm in Types) {
  852. if (tm == Types.VOID.toUpperCase()) {
  853. continue;
  854. }
  855. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(tm.toLowerCase())+'</div>';
  856. }
  857. for (var tm in Types) {
  858. if (tm == Types.VOID.toUpperCase()) {
  859. continue;
  860. }
  861. ret += '<div class="item">'
  862. + '<i class="dropdown icon"></i>'
  863. + LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())
  864. + '<div class="menu">'
  865. + '<div class="item" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())+' [ ] " data-type="'+tm+'" data-dimensions="1">[ ]</div>'
  866. + '<div class="item" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(tm.toLowerCase())+' [ ] [ ] " data-type="'+tm+'" data-dimensions="2">[ ] [ ] </div>'
  867. + '</div>'
  868. + '</div>';
  869. }
  870. ret += '</div></div>';
  871. ret += '<div class="parameter_div_edit"><span class="span_name_parameter label_enable_name_parameter">'+parameter_obj.name+'</span></div> ';
  872. ret += ' <i class="yellow inverted icon times remove_parameter"></i></div>';
  873. ret = $(ret);
  874. function_container.find('.container_parameters_list').append(ret);
  875. ret.find('.remove_parameter').on('click', function(e){
  876. removeParameter(function_obj, parameter_obj, ret);
  877. });
  878. ret.find('.ui.dropdown.parameter_type').dropdown({
  879. onChange: function(value, text, $selectedItem) {
  880. if ($selectedItem.data('dimensions')) {
  881. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
  882. } else {
  883. updateParameterType(parameter_obj, Types[$selectedItem.data('type')]);
  884. }
  885. },
  886. selectOnKeydown: false
  887. });
  888. ret.find('.label_enable_name_parameter').on('click', function(e){
  889. enableNameParameterUpdate(parameter_obj, ret, function_obj);
  890. });
  891. return ret;
  892. }
  893. function updateParameterName (parameter_var, new_name, parameter_obj_dom, function_obj) {
  894. if (parameter_var.name == new_name) {
  895. return;
  896. }
  897. if (isValidIdentifier(new_name)) {
  898. if (variableNameAlreadyExists(new_name, function_obj)) {
  899. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getUI('inform_valid_variable_duplicated'));
  900. } else {
  901. parameter_var.name = new_name;
  902. }
  903. } else {
  904. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getUI('inform_valid_name'));
  905. }
  906. }
  907. function variableNameAlreadyExists (name_var, function_obj) {
  908. if (function_obj.parameters_list) {
  909. for (var i = 0; i < function_obj.parameters_list.length; i++) {
  910. if (function_obj.parameters_list[i].name == name_var) {
  911. return true;
  912. }
  913. }
  914. }
  915. if (function_obj.variables_list) {
  916. for (var i = 0; i < function_obj.variables_list.length; i++) {
  917. if (function_obj.variables_list[i].name == name_var) {
  918. return true;
  919. }
  920. }
  921. }
  922. return false;
  923. }
  924. function updateFunctionName (function_var, new_name, function_obj_dom) {
  925. if (function_var.name == new_name) {
  926. return;
  927. }
  928. if (isValidIdentifier(new_name)) {
  929. if (functionNameAlreadyExists(new_name)) {
  930. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getUI('inform_valid_name_duplicated'));
  931. } else {
  932. function_var.name = new_name;
  933. }
  934. } else {
  935. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getUI('inform_valid_name'));
  936. }
  937. }
  938. function functionNameAlreadyExists (function_name) {
  939. for (var i = 0; i < window.program_obj.functions.length; i++) {
  940. if (window.program_obj.functions[i].name == function_name) {
  941. return true;
  942. }
  943. }
  944. return false;
  945. }
  946. function isValidIdentifier (identifier_str) {
  947. return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier_str);
  948. }
  949. var opened_name_parameter = false;
  950. var opened_input_parameter = null;
  951. function enableNameParameterUpdate (parameter_obj, parent_node, function_obj) {
  952. if (opened_name_parameter) {
  953. opened_input_parameter.focus();
  954. return;
  955. }
  956. opened_name_parameter = true;
  957. parent_node = $(parent_node);
  958. var input_field;
  959. parent_node.find('.span_name_parameter').text('');
  960. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+parameter_obj.name+"' />" );
  961. input_field.insertBefore(parent_node.find('.span_name_parameter'));
  962. input_field.on('input', function() {
  963. var inputWidth = input_field.textWidth()+10;
  964. opened_input_parameter = input_field;
  965. input_field.focus();
  966. var tmpStr = input_field.val();
  967. input_field.val('');
  968. input_field.val(tmpStr);
  969. input_field.css({
  970. width: inputWidth
  971. })
  972. }).trigger('input');
  973. input_field.focusout(function() {
  974. /// update array:
  975. if (input_field.val().trim()) {
  976. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  977. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  978. }
  979. input_field.off();
  980. input_field.remove();
  981. /// update elements:
  982. opened_name_parameter = false;
  983. opened_input_parameter = false;
  984. });
  985. input_field.on('keydown', function(e) {
  986. var code = e.keyCode || e.which;
  987. if(code == 13) {
  988. if (input_field.val().trim()) {
  989. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  990. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  991. }
  992. input_field.off();
  993. input_field.remove();
  994. /// update elements:
  995. opened_name_parameter = false;
  996. opened_input_parameter = false;
  997. }
  998. if(code == 27) {
  999. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1000. input_field.off();
  1001. input_field.remove();
  1002. /// update elements:
  1003. opened_name_parameter = false;
  1004. opened_input_parameter = false;
  1005. }
  1006. });
  1007. input_field.select();
  1008. }
  1009. var opened_name_function = false;
  1010. var opened_input = null;
  1011. var previousPadding = null;
  1012. function enableNameFunctionUpdate (function_obj, parent_node) {
  1013. if (opened_name_function) {
  1014. opened_input.focus();
  1015. return;
  1016. }
  1017. parent_node = $(parent_node);
  1018. parent_node.find('.span_name_function').text('');
  1019. var input_field;
  1020. if (!previousPadding) {
  1021. previousPadding = parent_node.find('.span_name_function').css('padding-left');
  1022. }
  1023. parent_node.find('.span_name_function').css('padding-left', '0');
  1024. parent_node.find('.span_name_function').css('padding-right', '0');
  1025. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+function_obj.name+"' />" );
  1026. input_field.insertBefore(parent_node.find('.span_name_function'));
  1027. input_field.on('input', function() {
  1028. var inputWidth = input_field.textWidth()+10;
  1029. opened_input = input_field;
  1030. input_field.focus();
  1031. var tmpStr = input_field.val();
  1032. input_field.val('');
  1033. input_field.val(tmpStr);
  1034. input_field.css({
  1035. width: inputWidth
  1036. })
  1037. }).trigger('input');
  1038. input_field.focusout(function() {
  1039. /// update array:
  1040. if (input_field.val().trim()) {
  1041. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1042. }
  1043. input_field.off();
  1044. input_field.remove();
  1045. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1046. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1047. parent_node.find('.span_name_function').text(function_obj.name);
  1048. /// update elements:
  1049. opened_name_function = false;
  1050. opened_input = false;
  1051. });
  1052. input_field.on('keydown', function(e) {
  1053. var code = e.keyCode || e.which;
  1054. if(code == 13) {
  1055. if (input_field.val().trim()) {
  1056. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1057. }
  1058. input_field.off();
  1059. input_field.remove();
  1060. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1061. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1062. parent_node.find('.span_name_function').text(function_obj.name);
  1063. /// update elements:
  1064. opened_name_function = false;
  1065. opened_input = false;
  1066. }
  1067. if(code == 27) {
  1068. input_field.off();
  1069. input_field.remove();
  1070. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1071. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1072. parent_node.find('.span_name_function').text(function_obj.name);
  1073. /// update elements:
  1074. opened_name_function = false;
  1075. opened_input = false;
  1076. }
  1077. });
  1078. input_field.select();
  1079. }
  1080. export function addFunctionChangeListener (callback) {
  1081. functionsChangeListeners.push(callback);
  1082. return functionsChangeListeners.length - 1;
  1083. }
  1084. export function addGlobalChangeListener (callback) {
  1085. globalChangeListeners.push(callback);
  1086. return globalChangeListeners.length - 1;
  1087. }
  1088. export function removeGlobalListener (index) {
  1089. globalChangeListeners.splice(index, 1);
  1090. }
  1091. export function removeFunctionListener (index) {
  1092. functionsChangeListeners.splice(index);
  1093. }