ghci.service.ts 15.7 KB
Newer Older
1
import { Injectable,ViewChild,ElementRef } from '@angular/core';
2
import { Router } from '@angular/router';
3
4
5
6
import { Observable, Subject } from 'rxjs/Rx';
import { WebsocketService } from './websocket.service';
import { AuthenticationService } from './authentication.service';
import { GHCI_URL } from '../config';
7
import { TranslateService } from '@ngx-translate/core';
8

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
declare var $:any;
declare var that :any ;
const regex = /^color (errores|input|output|logs) (\d)$/g;

import 'tippy.js/dist/tippy';

@Injectable()
export class GHCIService {
	public messages: Subject<any> = new Subject<any>();
	private connection = undefined;
	private cons = undefined;
	private modoAvanzado: boolean = false;     // indica si debe mostrarse todo lo que ocurre en el intérprete.
	private clear:boolean = false;
	private error :string ="";
	private warnings: any = [];
	private codemirrorRef :any = null;
25
	private warningStepReaded :number = 0;
26
27
28
29
	private waitingForError : boolean = false;
	private waitingForWarning : boolean = false;
	private waitingForWarning2 : boolean = false;
	private warningText :string = "";
Marcos Viera's avatar
Marcos Viera committed
30
	private errorText :string = "";
31
	private lastError : number = -1;
32
	private lastErrorFile :string = "";	
33
	private lastWarning :number = -1;
34
35
	private lastWarningFile :string = "";	
	private currentFile :string = "";
36
    translateService: any;
37
38
39
40
41

	private console_error_class : string = "jqconsole-asd";

	consoleBuffer = [];

42
43
	constructor(private authService:AuthenticationService,private router: Router, public translate: TranslateService){
		this.translateService = translate;
44
		console.log("contructor ghci");
45
		this.conectarWS(GHCI_URL, authService.getUser().cedula, authService.getToken(), authService.getLanguage());
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
		setInterval( this.checkConnection.bind(this), 5000);	
		setInterval( this.doPing.bind(this), 30000);	
	}

	setCodemirrorRef(instance){
		this.codemirrorRef = instance;
	}

	clearWarnings(){
		this.warnings = [];
	}

	getWarnings(){
		return this.warnings;
	}

62
	loadFile(fileId, fileName, dependencias) {
63
		this.waitingForWarning = true;
64
		this.currentFile = fileName;
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
		var message = {
			'token': this.authService.getToken(),
			'load': fileId,
			'dependencias' :[]

		};
		for(var i in dependencias){
			message.dependencias.push(dependencias[i]);
		};
		this.connection.send(JSON.stringify(message));
	}
	reiniciarInterprete(){
		var message = {
			'token': this.authService.getToken(),
			'restart': ''
		};
		console.log(message);
		this.connection.send(JSON.stringify(message));
	}

	regex: string  = '/(<svg.*\s*.*<\/svg>)/g';
	
	consoleRef:any;

89
	conectarWS(wsUrl, cedula, token, language){
90
		if(cedula && token && (!this.connection || this.connection.readyState == WebSocket.CLOSED)){
91
			this.connection = new WebSocket(wsUrl+"/"+cedula+"/"+token+"/"+language);
92
93
94
95

			this.connection.onopen = function(){
				console.log('Conexión con web socket exitosa');
			}
96
97
98
			this.connection.onclose = function(reason){
				//Codigo que indica la falta de permisos (sesion expirada por ejemplo)
				if(reason.code == 1008){
99
					this.router.navigate(['/'+this.translateService.get('i18n.code').value+'/login']);
100
101
102
				}
				console.log('Conexión con web socket cerrada',reason);
			}.bind(this)
103
104
105
106
			this.connection.onmessage = this.onMessage.bind(this);
		}
	}

107
108
109
110
111
112
	desconectarWS(){
		if(this.connection){
			this.connection.close();
		}
	}

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
	logConsole(text){
		if(this.consoleRef){
			this.consoleRef.Write(text, 'jqconsole-logs'); 
		}else{
			this.consoleBuffer.unshift({text: text, type:'jqconsole-logs'})
			setTimeout(this.checkConsole.bind(this),100);
		}
	}

	outputConsole(text){
		if(this.consoleRef){
			this.consoleRef.Write(text, 'jqconsole-output'); 
		}else{
			this.consoleBuffer.unshift({text: text, type:'jqconsole-output'})
			setTimeout(this.checkConsole.bind(this),100);
		}
	}

	errorConsole(text){
		if(this.consoleRef){
			this.consoleRef.Write(text, 'jqconsole-errors'); 
		}else{
			this.consoleBuffer.unshift({text: text, type:'jqconsole-errors'})
			setTimeout(this.checkConsole.bind(this),100);
		}
	}
Martín's avatar
Martín committed
139
	hayError(text){
140
141
142
		var line = -1;
		if(this.waitingForError){
			var line = this.lastError;
Marcos Viera's avatar
Marcos Viera committed
143
144
145
146
147
			var columna = this.errorText.split(`${this.translateService.get('i18n.codemirror.command.column').value}:`)[1].split("}")[0];
			var ErrorTextToShow = JSON.parse(text).resultado.split("OUT")[1].trim();

			var ErrorFinalText = `${this.translateService.get('i18n.codemirror.command.inColumn').value}` + columna + ": " + ErrorTextToShow;

148
			if((this.currentFile == this.lastErrorFile) && (this.codemirrorRef!==null)){
149
150
151
152
				var makeMarker = function() {
					var marker = document.createElement("div");
					marker.id = "error_" + line.toString();
					marker.style.width = "15px";
Marcos Viera's avatar
Marcos Viera committed
153
					marker.title = ErrorFinalText;
154
155
156
157
158
159
160
161
162
163
					marker.style.height = "15px";
					marker.style.marginLeft = "-5px";
					marker.style.cursor = "pointer";
					marker.style["background-image"] = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=')";
					marker.innerHTML = "<a href='@' title='cuidado , advertencia matefun'></a>";
					return marker;
				}
				this.codemirrorRef.setGutterMarker(line, "breakpoints", makeMarker());
				this.waitingForError = false;
				this.lastError = -1;
164
165
166
			}
		}else {
			try{
Marcos Viera's avatar
Marcos Viera committed
167
				var m = JSON.parse(text);
168
169
170
171
172
173
			      	var file = m.resultado
					.split(`${this.translateService.get('i18n.codemirror.command.outError').value}:`)[1]
					.trim()
					.split(`${this.translateService.get('i18n.object.file').value}:`)[1]
					.split(" ")[1]; 

Marcos Viera's avatar
Marcos Viera committed
174
175
176
177
178
179
				var line = m.resultado
					.split(`${this.translateService.get('i18n.codemirror.command.outError').value}:`)[1]
					.trim()
					.split(`${this.translateService.get('i18n.codemirror.command.line').value}:`)[1]
					.split(" ")[1]-1;

180
181
				this.waitingForError = true;	
				this.lastError = line;
182
				this.lastErrorFile = file;
Marcos Viera's avatar
Marcos Viera committed
183
				this.errorText = m.resultado.split(`${this.translateService.get('i18n.codemirror.command.outError').value}:`)[1].trim();
184
185
186
			}catch(err){
			}
			return false;
187
188
189
190

		}

	}
Martín's avatar
Martín committed
191
	
192
193
194
195
196
	resetGutters(){
		if(this.codemirrorRef!==null){
			this.codemirrorRef.clearGutter("breakpoints");
		}
	}
Martín's avatar
Martín committed
197
	
198
	hayWarnings(text){
199
		
200
		var line = -1;
201
202
203
204
205
206
207
208
		var m = JSON.parse(text);
		
		if(this.warningStepReaded===1){
			try{
				var warningText2 = m.resultado.split("OUT")[1].trim();
				this.warningStepReaded = 2;
				this.warningText = this.warningText + '\n\n' +  warningText2;

209
210
				var line = this.lastWarning;
				var title = this.warningText;
211

212
				var columna = title.split(`${this.translateService.get('i18n.codemirror.command.column').value}:`)[1].split("}")[0];
213
214
				var warningTextToShow = title.split("}")[1];

215
				var warningFinalText = `${this.translateService.get('i18n.codemirror.command.inColumn').value}` + columna + ": " + warningTextToShow;
216

217
				if((this.currentFile == this.lastWarningFile) && (this.codemirrorRef!==null)){
218
219
220
221
222
223
224
225
226
227
228
229
230
					var makeMarker = function() {
						var marker = document.createElement("div");
						marker.style.width = "15px";
						marker.style.height = "15px";
						marker.style.marginLeft = "-5px";
						marker.style.cursor = "pointer";
						marker.innerHTML = "<a href='@' title='cuidado , advertencia matefun'></a>";
						marker.title = warningFinalText;
						marker.style["background-image"] = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=')";
						marker.innerHTML = "";
						return marker;
					}
					this.codemirrorRef.setGutterMarker(line, "breakpoints", makeMarker());
231
				}
232
233
234

			}catch(err){

235
			}
236
237
238
239
		}

		if(this.warningStepReaded===0){

240
241
242
243
244
245
246
247
248
			try{ 
				var file = m.resultado
					.split(`${this.translateService.get('i18n.codemirror.command.outWarning').value}:`)[1]
					.trim()
					.split(`${this.translateService.get('i18n.object.file').value}:`)[1]
					.split(" ")[1]; 
					
			   
					
249
250
251
252
253
254
				// retrive line of warning
				var line = m.resultado
					.split(`${this.translateService.get('i18n.codemirror.command.outWarning').value}:`)[1]
					.trim()
					.split(`${this.translateService.get('i18n.codemirror.command.line').value}:`)[1]
					.split(" ")[1]-1;
255

256
				this.lastWarning = line;
257
				this.lastWarningFile = file;
258
				this.warnings.push(line);
259
				var warningText = m.resultado.split(`${this.translateService.get('i18n.codemirror.command.outWarning').value}:`)[1].trim();
260
261
262
263
				this.warningStepReaded = 1;
				this.warningText = warningText;
				if(this.waitingForWarning){

264
					this.outputConsole(`${this.translateService.get('i18n.msg.codemirror.consoleWarnings').value}\n`);
265
266
267
268
269
					this.waitingForWarning = false;	
				}

			} catch(err){

270
			}
271

272
		}
273

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
		
	}

	onMessage(e){
		if(this.modoAvanzado){
			this.logConsole('Respuesta: ' + e.data + '\n');
		}
		if(this.clear){
			this.clearConsole();
		}
		var server_message = e.data;

		if(this.hayError(server_message)){
			this.error = "Error";
		} else {
			this.error = "";
		}
291
292
293
294
295
296
297
298
		
		this.hayWarnings(server_message);

		if(this.warningStepReaded==2){
			this.warningStepReaded = 0;
			return;
		} else if(this.warningStepReaded==1){
			return;
299
300
301
302
303
		}

		var json_server_message = JSON.parse(server_message);
		if(json_server_message.tipo=='salida'){

304

305
306
307
308
309
310
311
			var line = json_server_message.resultado.trim();
			if(line.startsWith("OUT")){
				this.outputConsole(line.substring(3) + '\n');     
			}else if(line.startsWith("IN")){
				var promptText = line.substring(3);
				if(this.consoleRef===undefined){
					this.renderConsole();
312
				}
313
314
315
316
317
318
				this.consoleRef.SetPromptLabel(promptText);
				this.consoleRef.SetPromptText('');
				this.startPrompt.bind(this);
				this.startPrompt();
			}

319
			
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334

		} else if (json_server_message.tipo=='error'){
			if(this.modoAvanzado){
				this.errorConsole(json_server_message.resultado  + '\n');	
			}
		} else if (json_server_message.tipo == 'prompt'){
			// console.log(json_server_message.resultado);
			// console.log(this.consoleRef);
			// console.log(this.consoleRef.SetPromptLabel);
			// this.consoleRef.SetPromptLabel.bind(this);
			this.consoleRef.SetPromptLabel(json_server_message.resultado+'>');
			this.consoleRef.SetPromptText('');
			this.startPrompt.bind(this);
			this.startPrompt();
			// console.log(x);
335
336
337
		} else if (json_server_message.tipo == 'canvas' || 
			json_server_message.tipo == 'animacion' || 
			json_server_message.tipo == 'graph') {
338
			document.getElementById("FigurasBtn2D").click()
339
			this.focusConsole();
340
			this.messages.next(json_server_message);
341
342
		} else if  (json_server_message.tipo == 'canvas3D' || 
			json_server_message.tipo == 'animacion3D') {
Diego Rey's avatar
Diego Rey committed
343
			document.getElementById("FigurasBtn3D").click()
344
345
			this.focusConsole();
			this.messages.next(json_server_message);
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
		}

	}

	checkConsole(){
		if(this.consoleRef){
			while(this.consoleBuffer.length > 0){
				var bufferedMessage = this.consoleBuffer.pop();
				this.consoleRef.Write(bufferedMessage.text,bufferedMessage.type);
			}
		}else{
			setTimeout(this.checkConsole.bind(this),500);
		}
	}

	checkConnection(){
362
363
		var usuario = this.authService.getUser();
		var token = this.authService.getToken();
364
		var language = this.authService.getLanguage();
365
		if(usuario && token && (!this.connection || this.connection.readyState == WebSocket.CLOSED)){
366
			this.conectarWS(GHCI_URL, usuario.cedula, token, language);
367
368
369
370
		}		
	}

	doPing(){
371
372
		var token = this.authService.getToken();
		if(this.connection && this.connection.readyState == WebSocket.OPEN && token){
373
			var message = {
374
				'token': token,
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
				'ping': ''
			};
			this.connection.send(JSON.stringify(message));
		}		
	}

	sendLine(line) {
		if(line.trim()!==""){
			var message = {
				'token': this.authService.getToken(),
				'comando': line
			};
			console.log(message);
			if(this.connection && this.connection.readyState == WebSocket.OPEN){
				this.connection.send(JSON.stringify(message));
			}else{
391
				this.errorConsole("Sin conexión al servidor...\n");
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
			}
		}
	}

	startPrompt() {
		// Start the prompt with history enabled.
		this.jqconsole.Prompt(true, this.callback.bind(this));
	};

	focusConsole(){
		this.jqconsole.Focus();
	};

	clearConsole(){
		this.consoleRef.Reset();
		this.startPrompt.bind(this);
		this.startPrompt();
		this.clear = false;
	};

	callback(input){
		// Output input with the class jqconsole-output. 
		var ejecutar: boolean;
		ejecutar = this.procesarInput(input);
		if(ejecutar) {
			if(this.modoAvanzado){
				this.logConsole("Ejecutar: " + input + '\n');
			}
			this.sendLine.bind(this);
			this.sendLine(input);
		}
		this.startPrompt.bind(this);
		this.startPrompt();
	}

	procesarInput(input){
		var _input: string;
		var send: boolean = false;
		_input = input.trim().toLocaleLowerCase();
		if(_input==="limpiar"){
			this.clearConsole();
		} else if(_input==="modo avanzado") {
			this.modoAvanzado= true;
			this.logConsole("Modo avanzado activado\n");
		} else if(_input==="modo normal"){
			this.modoAvanzado= false;
			this.logConsole("Modo avanzado desactivado\n");
		} else if(_input==="listar colores"){
			this.outputConsole("1 - Azul\n");
			this.outputConsole("2 - Rojo\n");
			this.outputConsole("3 - Verde\n");
			this.outputConsole("4 - Verde oscuro\n");
			this.outputConsole("5 - Blanco\n");
			this.outputConsole("6 - Naranja\n");
			this.outputConsole("7 - Gris\n");
			this.outputConsole("8 - Gris oscuro\n");
			this.outputConsole("9 - Marrón\n");
		} else if(_input.match(regex)!==null) {
			var _tipoTexto :string = _input.split(" ")[1];
			var _color : string = input.split(" ")[2];
			this.jqconsoleColor(_color,_tipoTexto);
			if(this.modoAvanzado){
				this.logConsole("Color " + _tipoTexto + " seleccionado\n");	
			}
		} else {
			send = true;
		}	
		return send;
	}

	getCSSColorName(n){
		if(n==="1"){
			return "rgb(77, 77, 255)";
		} else if(n==="2"){
			return "rgb(255, 26, 26)";
		} else if (n==="3"){
			return "rgb(0, 179, 60)";
		} else if(n==="4"){
			return "rgb(0, 77, 0)";
		} else if(n==="5"){
			return "rgb(255, 255, 255)";
		} else if(n==="6"){
			return "rgb(255, 133, 51)";
		} else if(n==="7"){
			return "rgb(204, 204, 179)";
		} else if(n==="8"){
			return "rgb(102, 102, 102)";
		} else if(n==="9"){
			return "rgb(101, 27, 27)";
		}
	}

	getJQConsoleClass(jqconsoletext){
		if(jqconsoletext==="input"){
			return '.jqconsole-prompt';
		} else if(jqconsoletext==="error"){
			return '.jqconsole-error';
		} else if (jqconsoletext==="logs"){
			return '.jqconsole-logs';
		} else if(jqconsoletext==="output"){
			return '.jqconsole-output';
		}
	}

	jqconsoleColor(color, clase){
		var cssColor:string = this.getCSSColorName(color);
		var jqConsoleClass: string = this.getJQConsoleClass(clase);


		var style = document.createElement('style');
		style.type = 'text/css';
		style.innerHTML = jqConsoleClass +' { color: ' + cssColor + '; }';
		document.getElementsByTagName('head')[0].appendChild(style);

		if(jqConsoleClass==='.jqconsole-prompt'){
			var style2 = document.createElement('style');
			style2.type = 'text/css';
			style2.innerHTML = '.jqconsole-old-prompt { color: ' + cssColor + '; }';
			document.getElementsByTagName('head')[0].appendChild(style2);
		}

	}

	consola: any=undefined;
	renderConsole(){
		if(this.jqconsole){
			$('#console').replaceWith(this.consola);
		}else{
			if ($("#console").jqconsole!=undefined){ // Check if element has been found
				this.jqconsole = $('#console').jqconsole('');
				this.consoleRef = this.jqconsole;
				this.startPrompt.bind(this);
				this.startPrompt();
			} else {
				this.rendered();
			}
			this.consola = $("#console");
		}
	}

	jqconsole:any = undefined;
	rendered(){
		setTimeout(this.renderConsole.bind(this),1000);
	}



Martín's avatar
Martín committed
539
}