functions.js 55 KB

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