functions.js 55 KB

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