functions.js 53 KB

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