functions.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. // iVProg - www.usp.br/line/ivprog
  2. // LInE - Free Education, Private Data
  3. import { parserCodeVisual as textParser } from './../util/parseFromVisual.js'; //N Gleyce: it allows import IVPH file with comments (//)
  4. import { parserCodeVisual as modelParser } from './../util/codeParser.js'; //N Gleyce:
  5. import { Types } from './types';
  6. import * as Models from './ivprog_elements';
  7. import { LocalizedStrings } from './../services/localizedStringsService';
  8. import * as GlobalsManagement from './globals';
  9. import * as VariablesManagement from './variables';
  10. import * as CommandsManagement from './commands';
  11. import * as CodeManagement from './code_generator';
  12. import * as VariableValueMenu from './commands/variable_value_menu';
  13. import { DOMConsole } from './../io/domConsole';
  14. import { IVProgProcessor } from './../processor/ivprogProcessor';
  15. import WatchJS from 'melanke-watchjs';
  16. import { SemanticAnalyser } from '../processor/semantic/semanticAnalyser';
  17. import { IVProgAssessment } from '../assessment/ivprogAssessment';
  18. import * as AlgorithmManagement from './algorithm';
  19. import * as Utils from './utils';
  20. import { registerUserEvent, ActionTypes } from "./../services/userLog";
  21. import VersionInfo from './../../.ima_version.json';
  22. import * as TextEditor from "./text_editor";
  23. import { isValidIdentifier } from "./../util/utils";
  24. import { Modes } from '../processor/modes';
  25. import * as LanguageService from '../services/languageService.js'; // to use: var locStr = LanguageService.getCurrentLangFuncs().main_function; //leo
  26. const URLHELP = 'https://www.usp.br/line/ivprog/manual_pt/index.html'; // to be used in 'initVisualUI()' to link help button ('?') with iVProg help site
  27. var counter_new_functions = 0;
  28. var counter_new_parameters = 0;
  29. var ivprog_version = VersionInfo.version;
  30. const globalChangeListeners = [];
  31. const functionsChangeListeners = [];
  32. let proc = null;
  33. let domConsole = null;
  34. let _testCases = [];
  35. let isRunning = false;
  36. window.studentGrade = null;
  37. window.LocalizedStrings = LocalizedStrings;
  38. const program = new Models.Program();
  39. window.system_functions = [];
  40. // Adding math functions:
  41. window.system_functions.push(new Models.SystemFunction('$sin', 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('$cos', 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('$tan', 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('$sqrt', 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('$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)],
  50. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  51. window.system_functions.push(new Models.SystemFunction('$log', 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('$abs', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  54. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  55. window.system_functions.push(new Models.SystemFunction('$negate', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  56. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  57. window.system_functions.push(new Models.SystemFunction('$invert', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  58. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  59. window.system_functions.push(new Models.SystemFunction('$max', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  60. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  61. window.system_functions.push(new Models.SystemFunction('$min', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  62. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  63. window.system_functions.push(new Models.SystemFunction('$rand', Types.REAL, 0, [],
  64. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.math));
  65. // Adding text functions:
  66. window.system_functions.push(new Models.SystemFunction('$substring', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true),
  67. 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)],
  68. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  69. window.system_functions.push(new Models.SystemFunction('$length', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  70. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  71. window.system_functions.push(new Models.SystemFunction('$uppercase', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  72. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  73. window.system_functions.push(new Models.SystemFunction('$lowercase', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  74. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  75. window.system_functions.push(new Models.SystemFunction('$charAt', Types.CHAR, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true), new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  76. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.text));
  77. // Adding arrangement functions:
  78. 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)],
  79. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  80. 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)],
  81. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  82. 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)],
  83. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.arrangement));
  84. // Adding conversion functions:
  85. window.system_functions.push(new Models.SystemFunction('$isReal', 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('$isInt', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  88. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  89. window.system_functions.push(new Models.SystemFunction('$isBool', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  90. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  91. window.system_functions.push(new Models.SystemFunction('$castReal', Types.REAL, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  92. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  93. window.system_functions.push(new Models.SystemFunction('$castInt', Types.INTEGER, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  94. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  95. window.system_functions.push(new Models.SystemFunction('$castBool', Types.BOOLEAN, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  96. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  97. window.system_functions.push(new Models.SystemFunction('$castString', Types.TEXT, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  98. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  99. window.system_functions.push(new Models.SystemFunction('$castChar', Types.CHAR, 0, [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)],
  100. null, Models.SYSTEM_FUNCTIONS_CATEGORIES.conversion));
  101. 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');
  102. const mainFunction = new Models.Function(LocalizedStrings.getUI("start"), Types.VOID, 0, [], true, false);
  103. mainFunction.function_comment = new Models.Comment(LocalizedStrings.getUI('text_comment_main'));
  104. program.addFunction(mainFunction);
  105. window.program_obj = program;
  106. window.generator = CodeManagement.generate;
  107. window.runCodeAssessment = runCodeAssessment;
  108. window.renderAlgorithm = AlgorithmManagement.renderAlgorithm;
  109. window.insertContext = false;
  110. window.watchW = WatchJS;
  111. WatchJS.watch(window.program_obj.globals, function () {
  112. if (window.insertContext) {
  113. setTimeout(function() {
  114. AlgorithmManagement.renderAlgorithm();
  115. globalChangeListeners.forEach(x => x());
  116. }, 300);
  117. window.insertContext = false;
  118. } else {
  119. AlgorithmManagement.renderAlgorithm();
  120. globalChangeListeners.forEach(x => x());
  121. }
  122. }, 1);
  123. WatchJS.watch(window.program_obj.functions, function(){
  124. if (window.insertContext) {
  125. setTimeout(function(){
  126. AlgorithmManagement.renderAlgorithm();
  127. functionsChangeListeners.forEach( x => x());
  128. }, 300);
  129. window.insertContext = false;
  130. } else {
  131. AlgorithmManagement.renderAlgorithm();
  132. functionsChangeListeners.forEach( x => x());
  133. }
  134. }, 1);
  135. function addFunctionHandler () {
  136. if (window.program_obj.functions) {
  137. var in_use = false;
  138. do {
  139. in_use = false;
  140. var temp_name = LocalizedStrings.getUI('new_function') + '_' + counter_new_functions;
  141. window.program_obj.functions.forEach(function(el) {
  142. if (temp_name == el.name) {
  143. in_use = true;
  144. }
  145. })
  146. if (in_use)
  147. counter_new_functions++;
  148. } while (in_use);
  149. }
  150. 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')));
  151. program.addFunction(new_function);
  152. counter_new_functions ++;
  153. window.insertContext = true;
  154. registerUserEvent(new_function.name, ActionTypes.INSERT_FUNCTION);
  155. // var newe = renderFunction(new_function);
  156. renderFunction(new_function);
  157. /* newe.css('display', 'none'); newe.fadeIn(); */
  158. }
  159. function addParameter (function_obj, function_container/*, is_from_click = false*/) {
  160. if (function_obj.parameters_list == null) {
  161. function_obj.parameters_list = [];
  162. }
  163. if (function_obj.parameters_list) {
  164. var in_use = false;
  165. do {
  166. in_use = false;
  167. var temp_name = LocalizedStrings.getUI('new_parameter') + '_' + counter_new_parameters;
  168. function_obj.parameters_list.forEach(function(el) {
  169. if (temp_name == el.name) {
  170. in_use = true;
  171. }
  172. })
  173. if (in_use)
  174. counter_new_parameters++;
  175. } while (in_use);
  176. }
  177. const new_parameter = new Models.Variable(Types.INTEGER, LocalizedStrings.getUI("new_parameter") + "_" + counter_new_parameters);
  178. function_obj.parameters_list.push(new_parameter);
  179. counter_new_parameters ++;
  180. registerUserEvent(function_obj.name, ActionTypes.INSERT_FUNCTION_PARAM, new_parameter.name, Types.INTEGER, 0);
  181. //var newe = renderParameter(function_obj, new_parameter, function_container);
  182. renderParameter(function_obj, new_parameter, function_container);
  183. // if (is_from_click) {
  184. // newe.css('display', 'none');
  185. // newe.fadeIn();
  186. // }
  187. }
  188. function updateReturnType (function_obj, new_type, new_dimensions = 0) {
  189. registerUserEvent(function_obj.name, ActionTypes.CHANGE_FUNCTION_RETURN, new_type, new_dimensions);
  190. function_obj.return_type = new_type;
  191. function_obj.return_dimensions = new_dimensions;
  192. }
  193. function removeFunction (function_obj) {
  194. var index = program.functions.indexOf(function_obj);
  195. if (index > -1) {
  196. registerUserEvent(function_obj.name, ActionTypes.REMOVE_FUNCTION);
  197. program.functions.splice(index, 1);
  198. }
  199. }
  200. function minimizeFunction (function_obj) {
  201. function_obj.is_hidden = !function_obj.is_hidden;
  202. }
  203. function addHandlers (function_obj, function_container) {
  204. function_container.find('.ui.dropdown.function_return').dropdown({
  205. onChange: function(value, text, $selectedItem) {
  206. if ($selectedItem.data('dimensions')) {
  207. updateReturnType(function_obj, Types[$selectedItem.data('type')], $selectedItem.data('dimensions'));
  208. } else {
  209. updateReturnType(function_obj, Types[$selectedItem.data('type')]);
  210. }
  211. },
  212. selectOnKeydown: false
  213. });
  214. function_container.find( ".name_function_updated" ).on('click', function(e){
  215. enableNameFunctionUpdate(function_obj, function_container);
  216. });
  217. function_container.find( ".add_parameter_button" ).on('click', function(e){
  218. window.insertContext = true;
  219. addParameter(function_obj, function_container, true);
  220. });
  221. function_container.find('.menu_commands').dropdown({ on: 'hover' });
  222. function_container.find('.menu_commands a').on('click', function(evt){
  223. if (function_obj.commands == null || function_obj.commands.length == 0) {
  224. function_obj.commands = [];
  225. var new_cmd = CommandsManagement.genericCreateCommand($(this).data('command'));
  226. function_obj.commands.push(new_cmd);
  227. CommandsManagement.renderCommand(new_cmd, function_container.find('.commands_list_div'), 3, function_obj);
  228. registerUserEvent(function_obj.name, ActionTypes.INSERT_COMMAND, $(this).data('command'), '/', 0);
  229. } else {
  230. CommandsManagement.createFloatingCommand(function_obj, function_container, $(this).data('command'), evt);
  231. }
  232. });
  233. function_container.find('.add_var_button_function').on('click', function(e){
  234. window.insertContext = true;
  235. VariablesManagement.addVariable(function_obj, function_container, true);
  236. });
  237. function_container.find('.remove_function_button').on('click', function(e){
  238. removeFunction(function_obj);
  239. function_container.fadeOut();
  240. });
  241. function_container.find('.minimize_function_button').on('click', function(e){
  242. minimizeFunction(function_obj);
  243. if (function_obj.is_hidden) {
  244. function_container.find(".add_var_button_function").toggle();
  245. function_container.find(".inline_add_command").toggle();
  246. function_container.find(".function_area").slideToggle();
  247. } else {
  248. function_container.find(".function_area").slideToggle(function(){
  249. function_container.find(".add_var_button_function").toggle();
  250. function_container.find(".inline_add_command").toggle();
  251. });
  252. }
  253. });
  254. }
  255. // This function print the type that must be returned by the function.
  256. // It also create the "menu" item of type 'select' (to be filled).
  257. function renderFunctionReturn (function_obj, function_element) {
  258. var ret = '<div class="ui dropdown function_return">';
  259. if (function_obj.return_dimensions == 1) {
  260. ret += '<div class="text">'+ LocalizedStrings.getUI("vector") +': '+ LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`);
  261. ret += ' [ ] </div>';
  262. } else if (function_obj.return_dimensions == 2) {
  263. ret += '<div class="text">'+ LocalizedStrings.getUI("matrix") +': '+ LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`);
  264. ret += ' [ ] [ ] </div>';
  265. } else {
  266. ret += '<div class="text">'+LocalizedStrings.getUI(`type_${function_obj.return_type.toLowerCase()}`)+'</div>';
  267. }
  268. ret += '<div class="menu">';
  269. for (var tm in Types) {
  270. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions < 1 ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  271. }
  272. ret += '<div class="item ' + (function_obj.return_dimensions == 1 ? ' selected ' : '') + '">'
  273. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('vector')
  274. + '<div class="menu">';
  275. for (var tm in Types) {
  276. if (tm == Types.VOID.toUpperCase()) {
  277. continue;
  278. }
  279. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions == 1 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="1"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  280. }
  281. ret += '</div></div>';
  282. ret += '<div class="item ' + (function_obj.return_dimensions == 2 ? ' selected ' : '') + '">'
  283. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('matrix')
  284. + '<div class="menu">';
  285. for (var tm in Types) {
  286. if (tm == Types.VOID.toUpperCase()) {
  287. continue;
  288. }
  289. ret += '<div class="item ' + (function_obj.return_type == tm.toLowerCase() && function_obj.return_dimensions == 2 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('matrix')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="2"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  290. }
  291. ret += '</div></div>';
  292. ret += '</div></div>';
  293. ret = $(ret);
  294. function_element.find('.function_return').append(ret);
  295. }
  296. var cont = 0;
  297. export function renderFunction (function_obj) {
  298. var appender = '<div class="ui secondary segment function_div list-group-item function_cont_'+cont+'">';
  299. if (function_obj.function_comment) {
  300. //appender += renderComment(function_obj.function_comment, sequence, true, -1);
  301. }
  302. appender += '<span class="glyphicon glyphicon-move move_function" aria-hidden="true"><i class="icon sort alternate vertical"></i></span>';
  303. 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>')
  304. + '<button class="ui icon button tiny minimize_function_button"><i class="icon window minimize"></i></button>';
  305. appender += '<div class="function_signature_div">'+LocalizedStrings.getUI("function")+' ';
  306. if (function_obj.is_main) {
  307. appender += '<div class="function_name_div"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + LocalizedStrings.getUI('type_void') + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="span_name_function" >'+function_obj.name+'</span> </div> '
  308. + ' <span class="parethesis_function">( </span> <div class="ui large labels parameters_list">';
  309. } else {
  310. appender += '<div class="ui function_return"></div>';
  311. appender += '<div class="function_name_div function_name_div_updated"><span class="span_name_function name_function_updated">'+function_obj.name+'</span> </div> '
  312. + ' <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">';
  313. }
  314. appender += '</div> <span class="parethesis_function"> ) </span> </div>'
  315. + (function_obj.is_hidden ? ' <div class="function_area" style="display: none;"> ' : ' <div class="function_area"> ');
  316. appender += '<div class="ui add_var_context add_var_button_function" style="float: left;"> <div class="ui icon button purple"> ';
  317. 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>';
  318. appender += '</div></div>';
  319. appender += '<div class="ui top attached segment variables_list_div"></div>';
  320. appender += '<div class="ui bottom attached segment commands_list_div commands_cont_'+cont+'">'
  321. + '<div class="ui rail" style="width: 35px; margin-left: -36px;"><div class="ui sticky sticky_cont_'+cont+'" style="top: 50px !important;">';
  322. appender += '<div class="ui icon button dropdown menu_commands orange" > '
  323. + '<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>'
  324. + '<div class="menu"> ';
  325. appender += '<a class="item" data-command="'+Models.COMMAND_TYPES.reader+'"><i class="download icon"></i> ' +LocalizedStrings.getUI('text_read_var')+ '</a>'
  326. + '<a class="item" data-command="'+Models.COMMAND_TYPES.writer+'"><i class="upload icon"></i> '+LocalizedStrings.getUI('text_write_var')+'</a>'
  327. + '<a class="item" data-command="'+Models.COMMAND_TYPES.comment+'"><i class="quote left icon"></i> '+LocalizedStrings.getUI('text_comment')+'</a>'
  328. + '<a class="item" data-command="'+Models.COMMAND_TYPES.attribution+'"><i class="arrow left icon"></i> '+LocalizedStrings.getUI('text_attribution')+'</a>'
  329. + '<a class="item" data-command="'+Models.COMMAND_TYPES.functioncall+'"><i class="hand point right icon"></i> '+LocalizedStrings.getUI('text_functioncall')+'</a>'
  330. + '<a class="item" data-command="'+Models.COMMAND_TYPES.iftrue+'" ><i class="random icon"></i> '+LocalizedStrings.getUI('text_iftrue')+'</a>'
  331. + '<a class="item" data-command="'+Models.COMMAND_TYPES.repeatNtimes+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_repeatNtimes')+'</a>'
  332. + '<a class="item" data-command="'+Models.COMMAND_TYPES.whiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_whiletrue')+'</a>'
  333. + '<a class="item" data-command="'+Models.COMMAND_TYPES.dowhiletrue+'"><i class="sync icon"></i> '+LocalizedStrings.getUI('text_dowhiletrue')+'</a>'
  334. + '<a class="item" data-command="'+Models.COMMAND_TYPES.switch+'"><i class="list icon"></i> '+LocalizedStrings.getUI('text_switch')+'</a>'
  335. + '<a class="item" data-command="'+Models.COMMAND_TYPES.return+'"><i class="reply icon"></i> '+LocalizedStrings.getUI('text_btn_return')+'</a>'
  336. + '</div></div>';
  337. appender += '</div></div>' + '</div>';
  338. appender += '</div></div>';
  339. appender = $(appender);
  340. $('.all_functions').append(appender);
  341. appender.data('fun', function_obj);
  342. appender.find('.commands_list_div').data('fun', function_obj);
  343. renderFunctionReturn(function_obj, appender);
  344. addHandlers(function_obj, appender);
  345. // Rendering parameters:
  346. for (var j = 0; j < function_obj.parameters_list.length; j++) {
  347. renderParameter(function_obj, function_obj.parameters_list[j], appender);
  348. }
  349. // Rendering variables:
  350. for (var j = 0; j < function_obj.variables_list.length; j++) {
  351. VariablesManagement.renderVariable(appender, function_obj.variables_list[j], function_obj);
  352. }
  353. // Rendering commands:
  354. for (var j = 0; j < function_obj.commands.length; j++) {
  355. CommandsManagement.renderCommand(function_obj.commands[j], $(appender.find('.commands_list_div')[0]), 3, function_obj);
  356. }
  357. appender.find('.minimize_function_button').popup({
  358. content : LocalizedStrings.getUI("tooltip_hide_function"),
  359. delay: { show: 750, hide: 0 }
  360. });
  361. appender.find('.move_function').popup({
  362. content : LocalizedStrings.getUI("btn_drag_and_drop_function"),
  363. delay: { show: 1000, hide: 0 }
  364. });
  365. appender.find('.remove_function_button').popup({
  366. content : LocalizedStrings.getUI("btn_delete_function"),
  367. delay: { show: 750, hide: 0 }
  368. });
  369. appender.find('.add_var_button_function').popup({
  370. content : LocalizedStrings.getUI("btn_add_var"),
  371. delay: { show: 750, hide: 0 }
  372. });
  373. appender.find('a[data-command="attribution"]').popup({
  374. content : LocalizedStrings.getUI("tooltip_menu_attribution"),
  375. position: 'right center',
  376. delay: { show: 750, hide: 0 }
  377. });
  378. appender.find('a[data-command="functioncall"]').popup({
  379. content : LocalizedStrings.getUI("tooltip_menu_call_function"),
  380. position: 'right center',
  381. delay: { show: 750, hide: 0 }
  382. });
  383. appender.find('a[data-command="iftrue"]').popup({
  384. content : LocalizedStrings.getUI("tooltip_menu_if_else"),
  385. position: 'right center',
  386. delay: { show: 750, hide: 0 }
  387. });
  388. appender.find('a[data-command="comment"]').popup({
  389. content : LocalizedStrings.getUI("tooltip_menu_comments"),
  390. position: 'right center',
  391. delay: { show: 750, hide: 0 }
  392. });
  393. appender.find('a[data-command="reader"]').popup({
  394. content : LocalizedStrings.getUI("tooltip_menu_read"),
  395. position: 'right center',
  396. delay: { show: 750, hide: 0 }
  397. });
  398. appender.find('a[data-command="writer"]').popup({
  399. content : LocalizedStrings.getUI("tooltip_menu_write"),
  400. position: 'right center',
  401. delay: { show: 750, hide: 0 }
  402. });
  403. appender.find('a[data-command="repeatNtimes"]').popup({
  404. content : LocalizedStrings.getUI("tooltip_menu_repeat_n_times"),
  405. position: 'right center',
  406. delay: { show: 750, hide: 0 }
  407. });
  408. appender.find('a[data-command="whiletrue"]').popup({
  409. content : LocalizedStrings.getUI("tooltip_menu_repeat_whiletrue"),
  410. position: 'right center',
  411. delay: { show: 750, hide: 0 }
  412. });
  413. appender.find('a[data-command="dowhiletrue"]').popup({
  414. content : LocalizedStrings.getUI("tooltip_menu_repeat_dowhiletrue"),
  415. position: 'right center',
  416. delay: { show: 750, hide: 0 }
  417. });
  418. appender.find('a[data-command="switch"]').popup({
  419. content : LocalizedStrings.getUI("tooltip_menu_repeat_switch"),
  420. position: 'right center',
  421. delay: { show: 750, hide: 0 }
  422. });
  423. appender.find('a[data-command="return"]').popup({
  424. content : LocalizedStrings.getUI("tooltip_menu_repeat_return"),
  425. position: 'right center',
  426. delay: { show: 750, hide: 0 }
  427. });
  428. var function_index = program.functions.indexOf(function_obj);
  429. Sortable.create(appender.find(".variables_list_div")[0], {
  430. handle: '.ellipsis',
  431. animation: 100,
  432. ghostClass: 'ghost',
  433. group: 'local_vars_drag_' + function_index,
  434. onEnd: function (evt) {
  435. updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  436. }
  437. });
  438. addSortableHandler(appender.find(".commands_list_div")[0], function_index);
  439. if (!function_obj.is_main) {
  440. Sortable.create(appender.find(".container_parameters_list")[0], {
  441. handle: '.ellipsis',
  442. animation: 100,
  443. ghostClass: 'ghost',
  444. group: 'parameters_drag_' + program.functions.indexOf(function_obj),
  445. onEnd: function (evt) {
  446. updateSequenceParameters(evt.oldIndex, evt.newIndex, function_obj);
  447. }
  448. });
  449. }
  450. if (function_obj.commands.length > 0) {
  451. var teste = '.ui.sticky.sticky_cont_'+cont;
  452. $(teste).sticky({
  453. context: '.ui.bottom.attached.segment.commands_list_div.commands_cont_'+cont,
  454. scrollContext: '.ivprog_visual_panel',
  455. observeChanges: true,
  456. offset: 40,
  457. onStick: function (evt) {
  458. $(teste).css('top', '20px', 'important');
  459. },
  460. onBottom: function (evt) {
  461. $(teste).css('top', '20px', 'important');
  462. },
  463. onUnstick: function (evt) {
  464. $(teste).css('top', '20px', 'important');
  465. },
  466. onReposition: function (evt) {
  467. $(teste).css('top', '20px', 'important');
  468. },
  469. onScroll: function (evt) {
  470. $(teste).css('top', '20px', 'important');
  471. if (!isVisible($(teste), $(teste).parent())) {
  472. $(teste).removeClass('fixed');
  473. }
  474. },
  475. onTop: function (evt) {
  476. $(teste).css('top', '20px', 'important');
  477. }
  478. });
  479. }
  480. cont ++;
  481. appender.find('.add_parameter_button').popup({
  482. content : LocalizedStrings.getUI("text_add_parameters"),
  483. delay: { show: 750, hide: 0 }
  484. });
  485. return appender;
  486. }
  487. function isVisible (element, container) {
  488. var elementTop = $(element).offset().top,
  489. elementHeight = $(element).height(),
  490. containerTop = $(container).offset().top,
  491. containerHeight = $(container).height() - 30;
  492. return ((((elementTop - containerTop) + elementHeight) > 0) && ((elementTop - containerTop) < containerHeight));
  493. }
  494. window.evento_drag;
  495. function updateProgramObjDrag () {
  496. const nodes = Array.prototype.slice.call( $('.all_functions').children() );
  497. let function_index;
  498. var start_index;
  499. let function_obj;
  500. $(evento_drag.item).parentsUntil(".all_functions").each(function (index) {
  501. const ref = $(this);
  502. if (ref.hasClass('function_div')) {
  503. function_index = nodes.indexOf(this);
  504. start_index = index;
  505. function_obj = ref;
  506. }
  507. });
  508. const path_target = [];
  509. $(evento_drag.item).parentsUntil(".all_functions").each(function () {
  510. if ($(this).hasClass('command_container')) {
  511. path_target.push(this);
  512. }
  513. });
  514. if (path_target.length == 0) {
  515. // console.log('soltou na raiz, na posicao: ' + evento_drag.newIndex + ' mas ainda nao sei de onde saiu ');
  516. } else {
  517. // console.log('soltou dentro de algum bloco, sequencia vem logo abaixo (de baixo pra cima): ');
  518. // console.log(path_target);
  519. }
  520. var index_each = [];
  521. var path_relative = [];
  522. for (var i = path_target.length - 1; i >= 0; i --) {
  523. if (i == (path_target.length - 1)) { // it is on the root
  524. var indice_na_raiz = function_obj.find('.command_container').index(path_target[i]);
  525. } else {
  526. if ($(path_target[i + 1]).hasClass('iftrue')) {
  527. if ($(path_target[i]).parent().hasClass('commands_if')) {
  528. path_relative.push('if');
  529. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  530. } else {
  531. path_relative.push('else');
  532. index_each.push($(path_target[i]).parent().find('.command_container').index(path_target[i]));
  533. }
  534. } else if ($(path_target[i + 1]).hasClass('dowhiletrue')) {
  535. path_relative.push('dowhiletrue');
  536. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  537. } else if ($(path_target[i + 1]).hasClass('repeatNtimes')) {
  538. path_relative.push('repeatNtimes');
  539. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  540. } else if ($(path_target[i + 1]).hasClass('whiletrue')) {
  541. path_relative.push('whiletrue');
  542. index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  543. } else if ($(path_target[i + 1]).hasClass('switch')) {
  544. path_relative.push('switch');
  545. //index_each.push($(path_target[i + 1]).find('.command_container').index(path_target[i]));
  546. }
  547. }
  548. }
  549. // var index_in_block = -1;
  550. const is_in_else = $(evento_drag.item).parent().hasClass('commands_else');
  551. // index_in_block = $(evento_drag.item).parent().find('.command_container').index(evento_drag.item);
  552. const is_in_case_switch = $(evento_drag.item).parent().hasClass('case_commands_block');
  553. // Must find the element on the tree
  554. var command_start_point = window.program_obj.functions[function_index].commands[indice_na_raiz];
  555. var block_to_insert = command_start_point;
  556. for (var i = 0; i < index_each.length; i++) {
  557. if (path_relative[i] == "else") {
  558. block_to_insert = block_to_insert.commands_else[index_each[i]];
  559. } else if (path_relative[i] == "switch") {
  560. } else {
  561. block_to_insert = block_to_insert.commands_block[index_each[i]]
  562. }
  563. }
  564. //console.log('command_start_point', command_start_point);
  565. //console.log('block_to_insert', block_to_insert);
  566. // Now must insert the command on the tree, but must consider the 4 possible situations:
  567. // (1) it is inside one 'else' or; (2) it is inside a 'switch' or; (3) it is an standard case or; (4) it is on the root
  568. if (path_target.length == 0) { // it was released on the root
  569. window.program_obj.functions[function_index].commands.splice(evento_drag.newIndex - 1, 0, command_in_drag);
  570. } else if (is_in_else) {
  571. if (block_to_insert.commands_else) {
  572. block_to_insert.commands_else.splice(evento_drag.newIndex, 0, command_in_drag);
  573. } else {
  574. block_to_insert.commands_else = [];
  575. block_to_insert.commands_else.push(command_in_drag);
  576. }
  577. } else if (is_in_case_switch) {
  578. } else {
  579. // verificar se tem alguma coisa no bloco:
  580. if (block_to_insert.commands_block) {
  581. block_to_insert.commands_block.splice(evento_drag.newIndex, 0, command_in_drag);
  582. } else {
  583. block_to_insert.commands_block = [];
  584. block_to_insert.commands_block.push(command_in_drag);
  585. }
  586. }
  587. window.draging = false;
  588. renderAlgorithm();
  589. }
  590. function prepareDragHandler (evt) {
  591. window.draging = true;
  592. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  593. var function_index;
  594. var function_obj;
  595. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  596. if ($(this).hasClass('function_div')) {
  597. function_index = nodes.indexOf(this);
  598. function_obj = window.program_obj.functions[function_index];
  599. }
  600. });
  601. command_in_drag = $(evt.item).data("command");
  602. //console.log('$(evt.item).parent(): ');
  603. //console.log($(evt.item).parent());
  604. // Find wich on from 4 possible situations
  605. if ($(evt.item).parent().hasClass('commands_list_div')) { // it is no root
  606. if (function_obj.commands.indexOf(command_in_drag) > -1) {
  607. function_obj.commands.splice(function_obj.commands.indexOf(command_in_drag), 1);
  608. }
  609. } else if ($(evt.item).parent().hasClass('commands_else')) { // it is on 'else' command
  610. if ($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag) > -1) {
  611. $(evt.item).parent().data('command').commands_else.splice($(evt.item).parent().data('command').commands_else.indexOf(command_in_drag), 1);
  612. }
  613. } else if ($(evt.item).parent().hasClass('case_commands_block')) { // it is on 'switch':
  614. } else { // standard case
  615. if ($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag) > -1) {
  616. $(evt.item).parent().data('command').commands_block.splice($(evt.item).parent().data('command').commands_block.indexOf(command_in_drag), 1);
  617. }
  618. }
  619. }
  620. var command_in_drag;
  621. function addSortableHandler (element, id_function) {
  622. var n_group = 'commands_drag_' + id_function;
  623. Sortable.create(element, {
  624. handle: '.command_drag',
  625. ghostClass: 'ghost',
  626. animation: 300,
  627. group: {name: n_group},
  628. onEnd: function (evt) {
  629. var nodes = Array.prototype.slice.call( $('.all_functions').children() );
  630. var function_index;
  631. var function_obj;
  632. $(evt.item).parentsUntil(".all_functions").each(function (index) {
  633. if ($(this).hasClass('function_div')) {
  634. function_index = nodes.indexOf(this);
  635. function_obj = window.program_obj.functions[function_index];
  636. }
  637. });
  638. registerUserEvent(function_obj.name, ActionTypes.MOVE_COMMAND, $(evt.item).data('command').type, '/', 'from: ' + evt.oldIndex + ' to: ' + evt.newIndex);
  639. //updateSequenceLocals(evt.oldIndex, evt.newIndex, function_obj);
  640. var itemEl = evt.item; // dragged HTMLElement
  641. evt.to; // target list
  642. evt.from; // previous list
  643. evt.oldIndex; // element's old index within old parent
  644. evt.newIndex; // element's new index within new parent
  645. //console.log('::EVT::');
  646. //console.log(evt);
  647. window.evento_drag = evt;
  648. try {
  649. updateProgramObjDrag();
  650. } catch (e) {
  651. console.error(e);
  652. window.draging = false;
  653. }
  654. },
  655. onStart: function (evt) {
  656. //console.log("START::EVT::");
  657. //console.log(evt);
  658. //console.log("\n\ncommand_in_drag");
  659. try {
  660. prepareDragHandler(evt);
  661. } catch (e) {
  662. window.draging = false;
  663. }
  664. }
  665. });
  666. element = $(element);
  667. element.find(".iftrue").each(function( index ) {
  668. addSortableHandler($(this).find(".block_commands")[0], id_function);
  669. addSortableHandler($(this).find(".block_commands")[1], id_function);
  670. });
  671. element.find(".repeatNtimes").each(function( index ) {
  672. addSortableHandler($(this).find(".block_commands")[0], id_function);
  673. });
  674. element.find(".dowhiletrue").each(function( index ) {
  675. addSortableHandler($(this).find(".block_commands")[0], id_function);
  676. });
  677. element.find(".whiletrue").each(function( index ) {
  678. addSortableHandler($(this).find(".block_commands")[0], id_function);
  679. });
  680. element.find(".switch").each(function( index ) {
  681. $(this).find(".case_div").each(function( index ) {
  682. addSortableHandler($(this).find(".case_commands_block")[0], id_function);
  683. });
  684. });
  685. }
  686. export function initVisualUI () {
  687. // MUST USE CONST, LET, OR VAR !!!!!!
  688. // const mainDiv = $('#visual-main-div');
  689. // fill mainDiv with functions and globals...
  690. // renderAlgorithm()...
  691. console.log("functions.js!initVisualUI(): VersionInfo.version = " + ivprog_version); //leo
  692. domConsole = new DOMConsole("ivprog-term-div");
  693. domConsole.hide();
  694. $(document.getElementById("ivprog-term-div")).draggable()
  695. $('.add_function_button').on('click', () => {
  696. addFunctionHandler();
  697. }).popup({
  698. content : LocalizedStrings.getUI("text_add_function"),
  699. delay: { show: 750, hide: 0 }
  700. });
  701. $('.add_global_button').on('click', () => {
  702. window.insertContext = true;
  703. GlobalsManagement.addGlobal(program, true);
  704. });
  705. $('#run_button').on('click', function () {
  706. showStopButton();
  707. runCode();
  708. });
  709. $('#download_file_button').on('click', function () { downloadFile(); });
  710. $('#upload_file_button').on('click', function () {
  711. $('#ivph_file').click().off('change').change(uploadFile);
  712. });
  713. $('#stop_button').on('click', function () {
  714. showRunButton();
  715. stopExecution();
  716. });
  717. $('.visual_coding_button').on('click', () => { toggleVisualCoding();});
  718. $('.textual_coding_button').on('click', () => { toggleTextualCoding(); });
  719. $('.assessment').on('click', () => {
  720. is_iassign = true;
  721. runCodeAssessment();
  722. });
  723. $('.div_toggle_console').on('click', () => { toggleConsole(); });
  724. $('.expand_button').on('click', () => { full_screen(); });
  725. $('.help_button').on('click', () => {
  726. console.log("functions.js: initVisualUI(.): missing code to get the current language");
  727. try { //TODO get the current language
  728. // "pt" => URL = https://www.usp.br/line/ivprog/manual_pt
  729. // "en" => URL = https://www.usp.br/line/ivprog/en/manual_en
  730. //var locStr = LocalizedStrings.getInstance(); // Erro: TypeError: _services_localizedStringsService__WEBPACK_IMPORTED_MODULE_2__.LocalizedStrings.getInstance is not a function
  731. //var locStr = LanguageService.getCurrentLangFuncs().main_function; // Erro: TypeError: _services_languageService_js__WEBPACK_IMPORTED_MODULE_20__.getCurrentLangFuncs is not a function
  732. //var str = JSON.stringfy(locStr);
  733. //console.log("functions.js: initVisualUI(.): LocalizedStrings.getInstance=|" + str + "|");
  734. } catch (ex) { console.log("Erro: " + ex); }
  735. // window.open('https://www.usp.br/line/ivprog/', '_blank');
  736. window.open(URLHELP, '_blank'); // to link help button ('?') with iVProg help site
  737. });
  738. $('.main_title h2').prop('title', LocalizedStrings.getUI('text_ivprog_description'));
  739. var time_show = 750;
  740. $('.visual_coding_button').popup({
  741. content : LocalizedStrings.getUI("tooltip_visual"),
  742. delay: { show: time_show, hide: 0 }
  743. });
  744. $('.textual_coding_button').popup({
  745. content : LocalizedStrings.getUI("tooltip_textual"),
  746. delay: { show: time_show, hide: 0 }
  747. });
  748. $('.upload_file_button').popup({
  749. content : LocalizedStrings.getUI("tooltip_upload"),
  750. delay: { show: time_show, hide: 0 }
  751. });
  752. $('.download_file_button').popup({
  753. content : LocalizedStrings.getUI("tooltip_download"),
  754. delay: { show: time_show, hide: 0 }
  755. });
  756. // Not implemented yet, so removed for now... (those were presented disabled since initial version until 2024/10/10)
  757. // $('.undo_button').popup({ content : LocalizedStrings.getUI("tooltip_undo"), delay: { show: time_show, hide: 0 } });
  758. // $('.redo_button').popup({ content : LocalizedStrings.getUI("tooltip_redo"), delay: { show: time_show, hide: 0 } });
  759. $('.run_button').popup({
  760. content : LocalizedStrings.getUI("tooltip_run"),
  761. delay: { show: time_show, hide: 0 }
  762. });
  763. $('.assessment_button').popup({
  764. content : LocalizedStrings.getUI("tooltip_evaluate"),
  765. delay: { show: time_show, hide: 0 }
  766. });
  767. $('.help_button').popup({
  768. content : LocalizedStrings.getUI("tooltip_help") + ' - ' + LocalizedStrings.getUI("text_ivprog_version") + ' ' + ivprog_version,
  769. delay: { show: time_show, hide: 0 }
  770. });
  771. $('.add_global_button').popup({
  772. content : LocalizedStrings.getUI("tooltip_add_global"),
  773. delay: { show: time_show, hide: 0 }
  774. });
  775. $('.div_toggle_console').popup({
  776. content : LocalizedStrings.getUI("tooltip_console"),
  777. delay: { show: time_show, hide: 0 }
  778. });
  779. Sortable.create(listWithHandle, {
  780. handle: '.glyphicon-move',
  781. animation: 100,
  782. ghostClass: 'ghost',
  783. group: 'functions_divs_drag',
  784. onEnd: function (evt) { updateSequenceFunction(evt.oldIndex, evt.newIndex); }
  785. });
  786. var listGlobalsHandle = document.getElementById("listGlobalsHandle");
  787. Sortable.create(listGlobalsHandle, {
  788. handle: '.ellipsis',
  789. animation: 100,
  790. ghostClass: 'ghost',
  791. group: 'globals_divs_drag',
  792. onEnd: function (evt) { updateSequenceGlobals(evt.oldIndex, evt.newIndex); }
  793. });
  794. }
  795. export function setTestCases (testCases) {
  796. _testCases = testCases;
  797. }
  798. export function getTestCases () {
  799. // Deep clone of test cases to avoid unauthorized modification
  800. // TODO: It may be not possible to use this once custom test are fully implemented
  801. return JSON.parse(JSON.stringify(_testCases));
  802. }
  803. var is_iassign = false;
  804. function updateSequenceParameters (oldIndex, newIndex, function_obj) {
  805. function_obj.parameters_list.splice(newIndex, 0, function_obj.parameters_list.splice(oldIndex, 1)[0]);
  806. }
  807. function updateSequenceLocals (oldIndex, newIndex, function_obj) {
  808. function_obj.variables_list.splice(newIndex, 0, function_obj.variables_list.splice(oldIndex, 1)[0]);
  809. }
  810. function updateSequenceGlobals (oldIndex, newIndex) {
  811. program_obj.globals.splice(newIndex, 0, program_obj.globals.splice(oldIndex, 1)[0]);
  812. }
  813. function updateSequenceFunction (oldIndex, newIndex) {
  814. program_obj.functions.splice(newIndex, 0, program_obj.functions.splice(oldIndex, 1)[0]);
  815. }
  816. function runCodeAssessment () {
  817. if (isRunning) {
  818. // cannot run assessment or it's already running
  819. return -1;
  820. }
  821. let strCode = null;
  822. is_iassign = false;
  823. window.studentGrade = null;
  824. if (settingsProgrammingTypes == "textual") {
  825. strCode = TextEditor.getCode();
  826. } else {
  827. strCode = CodeManagement.generate();
  828. }
  829. if (strCode == null) {
  830. // No code, so no assessment
  831. return -1;
  832. }
  833. toggleConsole(true);
  834. try {
  835. const data = SemanticAnalyser.analyseFromSource(strCode);
  836. isRunning = true;
  837. const runner = new IVProgAssessment(data, _testCases, domConsole);
  838. runner.runTest().then(grade => {
  839. if (!is_iassign) {
  840. parent.getEvaluationCallback(grade);
  841. } else {
  842. is_iassign = false;
  843. }
  844. isRunning = false;
  845. }).catch( err => {
  846. console.log(err);
  847. isRunning = false;
  848. });
  849. } catch (error) {
  850. isRunning = false;
  851. domConsole.err(error.message);
  852. console.log(error);
  853. if (!is_iassign) {
  854. parent.getEvaluationCallback(0);
  855. } else {
  856. is_iassign = false;
  857. }
  858. }
  859. return 0;
  860. }
  861. function runCode () {
  862. if (isRunning) {
  863. return;
  864. }
  865. let strCode = null;
  866. if (settingsProgrammingTypes == "textual") {
  867. strCode = TextEditor.getCode();
  868. } else {
  869. strCode = CodeManagement.generate();
  870. }
  871. if (strCode == null) {
  872. return;
  873. }
  874. toggleConsole(true);
  875. // if(domConsole == null)
  876. // domConsole = new DOMConsole("#ivprog-term");
  877. //$("#ivprog-term").slideDown(500);
  878. try {
  879. const data = SemanticAnalyser.analyseFromSource(strCode);
  880. proc = new IVProgProcessor(data);
  881. proc.registerInput(domConsole);
  882. proc.registerOutput(domConsole);
  883. $("#ivprog-term").addClass('ivprog-term-active');
  884. isRunning = true;
  885. proc.interpretAST().then( _ => {
  886. scheduleCall(() => {
  887. if (domConsole.pending_writes.length == 0) {
  888. if (proc.mode === Modes.ABORT) {
  889. domConsole.info(LocalizedStrings.getMessage("aborted_execution"));
  890. } else {
  891. domConsole.info(LocalizedStrings.getMessage("success_execution"));
  892. }
  893. $("#ivprog-term").removeClass('ivprog-term-active');
  894. isRunning = false;
  895. proc = null;
  896. showRunButton();
  897. return true;
  898. }
  899. return false;
  900. },100);
  901. }).catch(err => {
  902. scheduleCall(() => {
  903. if (domConsole.pending_writes.length == 0) {
  904. if (err instanceof Error) {
  905. domConsole.err(err.message);
  906. } else {
  907. domConsole.err(err);
  908. }
  909. $("#ivprog-term").removeClass('ivprog-term-active');
  910. isRunning = false;
  911. proc = null;
  912. showRunButton();
  913. return true;
  914. }
  915. return false;
  916. },100);
  917. })
  918. } catch (error) {
  919. scheduleCall(() => {
  920. if (domConsole.pending_writes.length == 0) {
  921. isRunning = false;
  922. proc = null;
  923. showRunButton();
  924. domConsole.err(error.message);
  925. console.log(error);
  926. return true;
  927. }
  928. return false;
  929. },100);
  930. }
  931. }
  932. function toggleConsole (is_running) {
  933. if (is_running) {
  934. $('.ivprog-term-div').css('display', 'block');
  935. $('#ivprog-term').css('min-height', '160px');
  936. if (domConsole != null)
  937. domConsole.focus();
  938. //$('#ivprog-term').css('margin-top', '-170px');
  939. return;
  940. } else {
  941. domConsole.hide();
  942. return;
  943. }
  944. if ($('#ivprog-term').css('min-height') == '160px') {
  945. // esconder
  946. $('.ivprog-term-div').css('display', 'none');
  947. $('#ivprog-term').css('min-height', '0');
  948. //$('#ivprog-term').css('margin-top', '-30px');
  949. //$('#ivprog-term').css('padding', '5px');
  950. } else {
  951. // mostrar
  952. $('.ivprog-term-div').css('display', 'block');
  953. $('#ivprog-term').css('min-height', '160px');
  954. //$('#ivprog-term').css('margin-top', '-170px');
  955. }
  956. }
  957. // function waitToCloseConsole () {
  958. // domConsole.info("Aperte qualquer tecla para fechar...");
  959. // const p = new Promise((resolve, _) => {
  960. // domConsole.requestInput(resolve, true);
  961. // });
  962. // p.then( _ => {
  963. // domConsole.dispose();
  964. // domConsole = null;
  965. // $("#ivprog-term").hide();
  966. // })
  967. // }
  968. function toggleTextualCoding () {
  969. let code = null;
  970. if (settingsProgrammingTypes != "textual") {
  971. code = CodeManagement.generate();
  972. if (code == null) {
  973. return;
  974. }
  975. }
  976. $('.ivprog_visual_panel').css('display', 'none');
  977. $('.ivprog_textual_panel').css('display', 'block');
  978. $('.ivprog_textual_panel').removeClass('loading');
  979. TextEditor.updateEditor();
  980. if (code != null)
  981. TextEditor.setCode(code);
  982. //$('.ivprog_textual_code').text(code);
  983. $('.visual_coding_button').removeClass('active');
  984. $('.textual_coding_button').addClass('active');
  985. }
  986. function toggleVisualCoding () {
  987. $('.ivprog_textual_panel').addClass('loading');
  988. $('.ivprog_textual_panel').css('display', 'none');
  989. $('.ivprog_visual_panel').css('display', 'block');
  990. $('.textual_coding_button').removeClass('active');
  991. $('.visual_coding_button').addClass('active');
  992. }
  993. function removeParameter (function_obj, parameter_obj, parameter_container) {
  994. registerUserEvent(parameter_obj.name, ActionTypes.REMOVE_FUNCTION_PARAM, function_obj.name);
  995. var index = function_obj.parameters_list.indexOf(parameter_obj);
  996. if (index > -1) {
  997. window.insertContext = true;
  998. function_obj.parameters_list.splice(index, 1);
  999. }
  1000. $(parameter_container).fadeOut();
  1001. }
  1002. function updateParameterType (parameter_obj, new_type, function_name, new_dimensions = 0) {
  1003. registerUserEvent(parameter_obj.name, ActionTypes.CHANGE_PARAM_TYPE, function_name, new_type, new_dimensions);
  1004. parameter_obj.type = new_type;
  1005. parameter_obj.dimensions = new_dimensions;
  1006. if (new_dimensions > 0) {
  1007. parameter_obj.rows = new_dimensions;
  1008. parameter_obj.columns = 2;
  1009. }
  1010. }
  1011. function renderParameter (function_obj, parameter_obj, function_container) {
  1012. let ret = "";
  1013. ret += '<div class="ui label function_name_parameter pink"><i class="ui icon ellipsis vertical inverted"></i>';
  1014. if (parameter_obj.reference)
  1015. ret += '<input type="checkbox" checked class="by_reference">';
  1016. else
  1017. ret += '<input type="checkbox" class="by_copy">';
  1018. ret += '<div class="ui dropdown parameter_type">';
  1019. if (parameter_obj.dimensions > 0) {
  1020. ret += '<div class="text">'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${parameter_obj.type.toLowerCase()}`);
  1021. if (parameter_obj.dimensions == 1) {
  1022. ret += ' [ ] ';
  1023. } else {
  1024. ret += ' [ ] [ ] ';
  1025. }
  1026. ret += '</div>';
  1027. } else {
  1028. ret += '<div class="text">'+LocalizedStrings.getUI(`type_${parameter_obj.type.toLowerCase()}`)+'</div>';
  1029. }
  1030. ret += '<div class="menu">';
  1031. for (const tm in Types) {
  1032. if (tm == Types.VOID.toUpperCase()) {
  1033. continue;
  1034. }
  1035. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 0 ? ' selected ' : '') + '" data-type="'+tm+'" >'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  1036. }
  1037. ret += '<div class="item ' + (parameter_obj.dimensions == 1 ? ' selected ' : '') + '">'
  1038. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('vector')
  1039. + '<div class="menu">';
  1040. for (var tm in Types) {
  1041. if (tm == Types.VOID.toUpperCase()) {
  1042. continue;
  1043. }
  1044. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 1 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('vector')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="1"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  1045. }
  1046. ret += '</div></div>';
  1047. ret += '<div class="item ' + (parameter_obj.dimensions == 2 ? ' selected ' : '') + '">'
  1048. + '<i class="dropdown icon"></i>' + LocalizedStrings.getUI('matrix')
  1049. + '<div class="menu">';
  1050. for (var tm in Types) {
  1051. if (tm == Types.VOID.toUpperCase()) {
  1052. continue;
  1053. }
  1054. ret += '<div class="item ' + (parameter_obj.type == tm.toLowerCase() && parameter_obj.dimensions == 2 ? ' selected ' : '') + '" data-text="'+ LocalizedStrings.getUI('matrix')+':'+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+' [ ] " data-type="'+tm+'" data-dimensions="2"> '+LocalizedStrings.getUI(`type_${tm.toLowerCase()}`)+'</div>';
  1055. }
  1056. ret += '</div></div>';
  1057. ret += '</div></div>';
  1058. ret += '<div class="parameter_div_edit"><span class="span_name_parameter label_enable_name_parameter">'+parameter_obj.name+'</span></div> ';
  1059. ret += ' <i class="yellow inverted icon times remove_parameter"></i></div>';
  1060. ret = $(ret);
  1061. function_container.find('.container_parameters_list').append(ret);
  1062. ret.find('.remove_parameter').on('click', function(e){
  1063. removeParameter(function_obj, parameter_obj, ret);
  1064. });
  1065. ret.find('.ui.dropdown.parameter_type').dropdown({
  1066. onChange: function(_, __, $selectedItem) {
  1067. if ($selectedItem.data('dimensions')) {
  1068. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name, $selectedItem.data('dimensions'));
  1069. } else {
  1070. updateParameterType(parameter_obj, Types[$selectedItem.data('type')], function_obj.name);
  1071. }
  1072. },
  1073. selectOnKeydown: false
  1074. });
  1075. ret.find('.parameter_div_edit').on('click', function(e){
  1076. registerUserEvent(function_obj.name, ActionTypes.ENTER_CHANGE_PARAM_NAME, parameter_obj.name);
  1077. enableNameParameterUpdate(parameter_obj, ret, function_obj);
  1078. });
  1079. ret.find('input:checkbox').change(function() {
  1080. parameter_obj.reference = this.checked
  1081. AlgorithmManagement.renderAlgorithm();
  1082. });
  1083. ret.find('.by_reference').popup({
  1084. content : LocalizedStrings.getUI("text_parameter_reference"),
  1085. delay: { show: 750, hide: 0 }
  1086. });
  1087. ret.find('.by_copy').popup({
  1088. content : LocalizedStrings.getUI("text_parameter_copy"),
  1089. delay: { show: 750, hide: 0 }
  1090. });
  1091. return ret;
  1092. }
  1093. function updateParameterName (parameter_var, new_name, parameter_obj_dom, function_obj) {
  1094. if (parameter_var.name == new_name) {
  1095. return;
  1096. }
  1097. if (isValidIdentifier(new_name)) {
  1098. if (variableNameAlreadyExists(new_name, function_obj)) {
  1099. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getError('inform_valid_param_duplicated', [new_name, function_obj.name]));
  1100. } else {
  1101. registerUserEvent(function_obj.name, ActionTypes.RENAME_FUNCTION_PARAM, parameter_var.name, new_name);
  1102. parameter_var.name = new_name;
  1103. }
  1104. } else {
  1105. Utils.renderErrorMessage(parameter_obj_dom.find('.parameter_div_edit'), LocalizedStrings.getError('inform_valid_identifier'));
  1106. }
  1107. }
  1108. function variableNameAlreadyExists (name_var, function_obj) {
  1109. if (function_obj.parameters_list) {
  1110. for (var i = 0; i < function_obj.parameters_list.length; i++) {
  1111. if (function_obj.parameters_list[i].name == name_var) {
  1112. return true;
  1113. }
  1114. }
  1115. }
  1116. if (function_obj.variables_list) {
  1117. for (var i = 0; i < function_obj.variables_list.length; i++) {
  1118. if (function_obj.variables_list[i].name == name_var) {
  1119. return true;
  1120. }
  1121. }
  1122. }
  1123. return false;
  1124. }
  1125. function updateFunctionName (function_var, new_name, function_obj_dom) {
  1126. if (function_var.name == new_name) {
  1127. return;
  1128. }
  1129. if (isValidIdentifier(new_name)) {
  1130. if (functionNameAlreadyExists(new_name)) {
  1131. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getError('inform_valid_function_duplicated', [new_name]));
  1132. } else {
  1133. registerUserEvent(function_var.name, ActionTypes.RENAME_FUNCTION, new_name);
  1134. function_var.name = new_name;
  1135. }
  1136. } else {
  1137. Utils.renderErrorMessage(function_obj_dom.find('.function_name_div'), LocalizedStrings.getError('inform_valid_identifier'));
  1138. }
  1139. }
  1140. function functionNameAlreadyExists (function_name) {
  1141. for (var i = 0; i < window.program_obj.functions.length; i++) {
  1142. if (window.program_obj.functions[i].name == function_name) {
  1143. return true;
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. var opened_name_parameter = false;
  1149. var opened_input_parameter = null;
  1150. function enableNameParameterUpdate (parameter_obj, parent_node, function_obj) {
  1151. if (opened_name_parameter) {
  1152. opened_input_parameter.focus();
  1153. return;
  1154. }
  1155. opened_name_parameter = true;
  1156. parent_node = $(parent_node);
  1157. var input_field;
  1158. parent_node.find('.span_name_parameter').text('');
  1159. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+parameter_obj.name+"' />" );
  1160. input_field.insertBefore(parent_node.find('.span_name_parameter'));
  1161. input_field.on('input', function() {
  1162. var inputWidth = input_field.textWidth()+10;
  1163. opened_input_parameter = input_field;
  1164. input_field.focus();
  1165. var tmpStr = input_field.val();
  1166. input_field.val('');
  1167. input_field.val(tmpStr);
  1168. input_field.css({
  1169. width: inputWidth
  1170. })
  1171. }).trigger('input');
  1172. input_field.focusout(function() {
  1173. /// update array:
  1174. if (input_field.val().trim()) {
  1175. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1176. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1177. }
  1178. input_field.off();
  1179. input_field.remove();
  1180. /// update elements:
  1181. opened_name_parameter = false;
  1182. opened_input_parameter = false;
  1183. });
  1184. input_field.on('keydown', function(e) {
  1185. var code = e.keyCode || e.which;
  1186. if(code == 13) {
  1187. if (input_field.val().trim()) {
  1188. updateParameterName(parameter_obj, input_field.val().trim(), parent_node, function_obj);
  1189. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1190. }
  1191. input_field.off();
  1192. input_field.remove();
  1193. /// update elements:
  1194. opened_name_parameter = false;
  1195. opened_input_parameter = false;
  1196. }
  1197. if(code == 27) {
  1198. parent_node.find('.span_name_parameter').text(parameter_obj.name);
  1199. input_field.off();
  1200. input_field.remove();
  1201. /// update elements:
  1202. opened_name_parameter = false;
  1203. opened_input_parameter = false;
  1204. }
  1205. });
  1206. input_field.select();
  1207. }
  1208. var opened_name_function = false;
  1209. var opened_input = null;
  1210. var previousPadding = null;
  1211. function enableNameFunctionUpdate (function_obj, parent_node) {
  1212. if (opened_name_function) {
  1213. opened_input.focus();
  1214. return;
  1215. }
  1216. parent_node = $(parent_node);
  1217. parent_node.find('.span_name_function').text('');
  1218. var input_field;
  1219. if (!previousPadding) {
  1220. previousPadding = parent_node.find('.span_name_function').css('padding-left');
  1221. }
  1222. parent_node.find('.span_name_function').css('padding-left', '0');
  1223. parent_node.find('.span_name_function').css('padding-right', '0');
  1224. input_field = $( "<input type='text' class='width-dynamic input_name_function' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' value='"+function_obj.name+"' />" );
  1225. input_field.insertBefore(parent_node.find('.span_name_function'));
  1226. input_field.on('input', function() {
  1227. var inputWidth = input_field.textWidth()+10;
  1228. opened_input = input_field;
  1229. input_field.focus();
  1230. var tmpStr = input_field.val();
  1231. input_field.val('');
  1232. input_field.val(tmpStr);
  1233. input_field.css({
  1234. width: inputWidth
  1235. })
  1236. }).trigger('input');
  1237. input_field.focusout(function() {
  1238. /// update array:
  1239. if (input_field.val().trim()) {
  1240. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1241. }
  1242. input_field.off();
  1243. input_field.remove();
  1244. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1245. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1246. parent_node.find('.span_name_function').text(function_obj.name);
  1247. /// update elements:
  1248. opened_name_function = false;
  1249. opened_input = false;
  1250. });
  1251. input_field.on('keydown', function(e) {
  1252. var code = e.keyCode || e.which;
  1253. if(code == 13) {
  1254. if (input_field.val().trim()) {
  1255. updateFunctionName(function_obj, input_field.val().trim(), parent_node);
  1256. }
  1257. input_field.off();
  1258. input_field.remove();
  1259. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1260. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1261. parent_node.find('.span_name_function').text(function_obj.name);
  1262. /// update elements:
  1263. opened_name_function = false;
  1264. opened_input = false;
  1265. }
  1266. if(code == 27) {
  1267. input_field.off();
  1268. input_field.remove();
  1269. parent_node.find('.span_name_function').css('padding-left', previousPadding);
  1270. parent_node.find('.span_name_function').css('padding-right', previousPadding);
  1271. parent_node.find('.span_name_function').text(function_obj.name);
  1272. /// update elements:
  1273. opened_name_function = false;
  1274. opened_input = false;
  1275. }
  1276. });
  1277. input_field.select();
  1278. }
  1279. export function addFunctionChangeListener (callback) {
  1280. functionsChangeListeners.push(callback);
  1281. return functionsChangeListeners.length - 1;
  1282. }
  1283. export function addGlobalChangeListener (callback) {
  1284. globalChangeListeners.push(callback);
  1285. return globalChangeListeners.length - 1;
  1286. }
  1287. export function removeGlobalListener (index) {
  1288. globalChangeListeners.splice(index, 1);
  1289. }
  1290. export function removeFunctionListener (index) {
  1291. functionsChangeListeners.splice(index);
  1292. }
  1293. function scheduleCall (callback, time) {
  1294. const scheduled_call = () => {
  1295. const id = setInterval(() => {
  1296. if(callback()) {
  1297. clearInterval(id);
  1298. }
  1299. }, time)
  1300. }
  1301. scheduled_call();
  1302. }
  1303. function showRunButton () {
  1304. document.getElementById('run_button').style.display = 'inline';
  1305. document.getElementById('stop_button').style.display = 'none';
  1306. }
  1307. function showStopButton () {
  1308. document.getElementById('run_button').style.display = 'none';
  1309. document.getElementById('stop_button').style.display = 'inline';
  1310. }
  1311. function stopExecution () {
  1312. domConsole.clearPendingWrites();
  1313. domConsole.cancelPendingInputRequests();
  1314. if(!isRunning) {
  1315. return;
  1316. }
  1317. proc.mode = Modes.ABORT;
  1318. }
  1319. function downloadFile () {
  1320. var contentToSend = '{}\n::algorithm::';
  1321. contentToSend = generator();
  1322. var date = new Date();
  1323. var temp = date.toISOString().split('T')[0] + "_" + date.toTimeString().split(' ')[0].replaceAll(':', '-');
  1324. var blob = new Blob([contentToSend], { type: "text/plain;charset=utf-8" });
  1325. saveAs(blob, "ivprog-exported_" + temp + ".ivph");
  1326. }
  1327. // Upload file IVPH
  1328. function uploadFile (evt) {
  1329. var oFReader = new FileReader();
  1330. //N oFReader.readAsText(document.getElementById("ivph_file").files[0]);
  1331. oFReader.readAsText(document.getElementById("ivph_file").files[0], "UTF-8"); //N Gleyce
  1332. oFReader.onload = function (oFREvent) {
  1333. var txt = oFREvent.target.result;
  1334. try {
  1335. if (txt.indexOf("::algorithm::") >= 0 || txt.indexOf("\"test_cases\"") >= 0) {
  1336. //leo/lucas Version with "test-cases": { "version": "x.y",\n "code": ... \n "test_cases":...
  1337. prepareActivityToStudent(txt, true); // in ./src/ivprog/js/iassign-integration-functions.js
  1338. console.debug("js/visualUI/functions.js!uploadFile(.): code=" + txt.code);
  1339. }
  1340. else {
  1341. //N ivprogCore.setPreviousAlgorithm(txt);
  1342. //N window.renderAlgorithm();
  1343. //N Gleyce: start
  1344. // First try the old iVProg syntax to program (translate texto to data object)
  1345. console.log("js/visualUI/functions.js!uploadFile(.): read IVPH (allow comment)");
  1346. const code_obj = textParser(txt);
  1347. if (code_obj) {
  1348. // If succeed, translate data objects to visual block
  1349. modelParser(code_obj);
  1350. // Render algorithm into the visual interface
  1351. window.renderAlgorithm();
  1352. } else {
  1353. // If first try failed, present a warning
  1354. console.error("js/visualUI/functions.js: failed in the translation from texto to iVProg code");
  1355. alert("Something was wrong! Please, check if the syntax code of your file is valid to iVProg");
  1356. }
  1357. //N Gleyce: end
  1358. }
  1359. } catch (e) {
  1360. console.log(e)
  1361. }
  1362. };
  1363. }