functions.js 51 KB

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