functions.js 52 KB

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