functions.js 55 KB

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