1
0

functions.js 53 KB

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