functions.js 55 KB

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