Synchronet now requires the libarchive development package (e.g. libarchive-dev on Debian-based Linux distros, libarchive.org for more info) to build successfully.

ansi_cio.c 23.7 KB
Newer Older
1
/* $Id: ansi_cio.c,v 1.86 2020/04/13 18:36:21 deuce Exp $ */
deuce's avatar
deuce committed
2 3 4 5 6

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
7
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
deuce's avatar
deuce committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *																			*
 * This library is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU Lesser General Public License		*
 * as published by the Free Software Foundation; either version 2			*
 * of the License, or (at your option) any later version.					*
 * See the GNU Lesser General Public License for more details: lgpl.txt or	*
 * http://www.fsf.org/copyleft/lesser.html									*
 *																			*
 * Anonymous FTP access to the most recent released source is available at	*
 * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net	*
 *																			*
 * Anonymous CVS access to the development source and modification history	*
 * is available at cvs.synchro.net:/cvsroot/sbbs, example:					*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login			*
 *     (just hit return, no password is necessary)							*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src		*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * You are encouraged to submit any modifications (preferably in Unix diff	*
 * format) via e-mail to mods@synchro.net									*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

34 35
#include <fcntl.h>
#include <stdarg.h>
rswindell's avatar
rswindell committed
36
#include <stdlib.h>	/* malloc */
37 38 39

#include <genwrap.h>
#include <threadwrap.h>
40
#include <semwrap.h>
41 42

#ifdef __unix__
rswindell's avatar
rswindell committed
43 44
	#include <termios.h>
	struct termios tio_default;				/* Initial term settings */
45 46
#endif

47 48 49 50 51 52 53 54 55 56
#ifdef _WIN32
	#ifndef ENABLE_VIRTUAL_TERMINAL_INPUT
	#define ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200
	#endif
	#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
	#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
	#endif
#endif


57
#include "ciolib.h"
58
#include "ansi_cio.h"
deuce's avatar
deuce committed
59

deuce's avatar
deuce committed
60
int	CIOLIB_ANSI_TIMEOUT=500;
61
int  (*ciolib_ansi_readbyte_cb)(void)=ansi_readbyte_cb;
62
int  (*ciolib_ansi_writebyte_cb)(const unsigned char ch)=ansi_writebyte_cb;
63
int  (*ciolib_ansi_initio_cb)(void)=ansi_initio_cb;
64
int  (*ciolib_ansi_writestr_cb)(const unsigned char *str, size_t len)=ansi_writestr_cb;
deuce's avatar
deuce committed
65

66 67 68 69 70
static sem_t	got_key;
static sem_t	got_input;
static sem_t	used_input;
static sem_t	goahead;
static sem_t	need_key;
71
static BOOL	sent_ga=FALSE;
72 73
static int ansix=1;
static int ansiy=1;
74

75 76
static int ansi_got_row=0;
static int doorway_enabled=0;
77 78 79

const int 	ansi_colours[8]={0,4,2,6,1,5,3,7};
static WORD		ansi_inch;
80
static int		ansi_raw_inch;
81 82
static WORD	*ansivmem;
static int		force_move=1;
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

/* Control sequence table definitions. */
typedef struct
{
   char *pszSequence;
   int chExtendedKey;
} tODKeySequence;

#define ANSI_KEY_UP		72<<8
#define ANSI_KEY_DOWN	80<<8
#define ANSI_KEY_RIGHT	0x4d<<8
#define ANSI_KEY_LEFT	0x4b<<8
#define ANSI_KEY_HOME	0x47<<8
#define ANSI_KEY_END	0x4f<<8
#define ANSI_KEY_F1		0x3b<<8
#define ANSI_KEY_F2		0x3c<<8
#define ANSI_KEY_F3		0x3d<<8
#define ANSI_KEY_F4		0x3e<<8
#define ANSI_KEY_F5		0x3f<<8
#define ANSI_KEY_F6		0x40<<8
#define ANSI_KEY_F7		0x41<<8
#define ANSI_KEY_F8		0x42<<8
#define ANSI_KEY_F9		0x43<<8
#define ANSI_KEY_F10	0x44<<8
#define ANSI_KEY_PGUP	0x49<<8
#define ANSI_KEY_PGDN	0x51<<8
#define ANSI_KEY_INSERT	0x52<<8
#define ANSI_KEY_DELETE	0x53<<8
deuce's avatar
deuce committed
111 112
#define ANSI_KEY_F11	0x85<<8
#define ANSI_KEY_F12	0x86<<8
113

114
static tODKeySequence ODaKeySequences[] =
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
{
   /* VT-52 control sequences. */
   {"\033A", ANSI_KEY_UP},
   {"\033B", ANSI_KEY_DOWN},
   {"\033C", ANSI_KEY_RIGHT},
   {"\033D", ANSI_KEY_LEFT},
   {"\033H", ANSI_KEY_HOME},
   {"\033K", ANSI_KEY_END},
   {"\033P", ANSI_KEY_F1},
   {"\033Q", ANSI_KEY_F2},
   {"\033?w", ANSI_KEY_F3},
   {"\033?x", ANSI_KEY_F4},
   {"\033?t", ANSI_KEY_F5},
   {"\033?u", ANSI_KEY_F6},
   {"\033?q", ANSI_KEY_F7},
   {"\033?r", ANSI_KEY_F8},
   {"\033?p", ANSI_KEY_F9},

   /* Control sequences common to VT-100/VT-102/VT-220/VT-320/ANSI. */
   {"\033[A", ANSI_KEY_UP},
   {"\033[B", ANSI_KEY_DOWN},
   {"\033[C", ANSI_KEY_RIGHT},
   {"\033[D", ANSI_KEY_LEFT},
   {"\033[M", ANSI_KEY_PGUP},
   {"\033[H\x1b[2J", ANSI_KEY_PGDN},
   {"\033[H", ANSI_KEY_HOME},
   {"\033[K", ANSI_KEY_END},
   {"\033OP", ANSI_KEY_F1},
   {"\033OQ", ANSI_KEY_F2},
   {"\033OR", ANSI_KEY_F3},
   {"\033OS", ANSI_KEY_F4},

   /* VT-220/VT-320 specific control sequences. */
148 149 150 151 152 153
   {"\033[1~",  ANSI_KEY_HOME}, /* Windows XP terminal.exe.  Is actually FIND */
   {"\033[2~",  ANSI_KEY_INSERT},
   {"\033[3~",  ANSI_KEY_DELETE},
   {"\033[4~",  ANSI_KEY_END},  /* Windows XP terminal.exe.  Is actually SELECT */
   {"\033[5~",  ANSI_KEY_PGUP},
   {"\033[6~",  ANSI_KEY_PGDN},
154 155 156 157 158
   {"\033[17~", ANSI_KEY_F6},
   {"\033[18~", ANSI_KEY_F7},
   {"\033[19~", ANSI_KEY_F8},
   {"\033[20~", ANSI_KEY_F9},
   {"\033[21~", ANSI_KEY_F10},
159 160
   {"\033[23~", ANSI_KEY_F11},
   {"\033[24~", ANSI_KEY_F12},
161

162 163 164 165 166 167 168 169 170
   /* XTerm specific control sequences */
   {"\033[15~", ANSI_KEY_F5},

   /* Old, deprecated XTerm specific control sequences */
   {"\033[11~", ANSI_KEY_F1},
   {"\033[12~", ANSI_KEY_F2},
   {"\033[13~", ANSI_KEY_F3},
   {"\033[14~", ANSI_KEY_F4},

171 172 173 174 175 176 177 178 179 180
   /* ANSI-specific control sequences. */
   {"\033[L", ANSI_KEY_HOME},
   {"\033Ow", ANSI_KEY_F3},
   {"\033Ox", ANSI_KEY_F4},
   {"\033Ot", ANSI_KEY_F5},
   {"\033Ou", ANSI_KEY_F6},
   {"\033Oq", ANSI_KEY_F7},
   {"\033Or", ANSI_KEY_F8},
   {"\033Op", ANSI_KEY_F9},

181 182 183 184 185 186
   /* ECMA 048-specific control sequences. */
   {"\033[V", ANSI_KEY_PGUP},
   {"\033[U", ANSI_KEY_PGDN},
   {"\033[@", ANSI_KEY_INSERT},
   
   
187 188 189 190 191 192 193
   /* PROCOMM-specific control sequences (non-keypad alternatives). */
   {"\033OA", ANSI_KEY_UP},
   {"\033OB", ANSI_KEY_DOWN},
   {"\033OC", ANSI_KEY_RIGHT},
   {"\033OD", ANSI_KEY_LEFT},
   {"\033OH", ANSI_KEY_HOME},
   {"\033OK", ANSI_KEY_END},
deuce's avatar
deuce committed
194

195 196 197 198
   /* Terminator */
   {"",0}
};

deuce's avatar
deuce committed
199
#ifdef NEEDS_CFMAKERAW
200
static void
deuce's avatar
deuce committed
201 202 203 204 205 206 207 208 209 210
cfmakeraw(struct termios *t)
{
	t->c_iflag &= ~(IMAXBEL|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
	t->c_oflag &= ~OPOST;
	t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
	t->c_cflag &= ~(CSIZE|PARENB);
	t->c_cflag |= CS8;
}
#endif

211 212
/* Do NOT call this to output to the last column of the last row. */
/* ONLY call this for chars which will move the cursor */
213
static void ansi_sendch(char ch)
214 215 216
{
	if(!ch)
		ch=' ';
217 218
	ansix++;
	if(ansix>cio_textinfo.screenwidth) {
219 220
		/* Column 80 sux0rz */
		force_move=1;
221 222 223 224 225
		ansix=1;
		ansiy++;
		if(ansiy>cio_textinfo.screenheight) {
			ansix=cio_textinfo.screenwidth;
			ansiy=cio_textinfo.screenheight;
226
		}
227
	}
228
	if(doorway_enabled && ch < ' ')
229 230
		ciolib_ansi_writebyte_cb(0);
	ciolib_ansi_writebyte_cb((unsigned char)ch);
231
	/* We sent a control char... better make the next movement explicit */
232 233 234 235 236 237 238
	if(ch<' ' && ch > 0) {
		if(doorway_enabled) {
			/* In doorway mode, some chars may want to force movement... */
		}
		else
			force_move=1;
	}
239 240
}

241
static void ansi_sendstr(const char *str,int len)
242 243 244
{
	if(len==-1)
		len=strlen(str);
245
	if(len)
246
		ciolib_ansi_writestr_cb((unsigned char *)str, (size_t)len);
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

static void ansi_gotoxy_abs(int x, int y)
{
	char str[16];

	str[0]=0;
	if(x < 1
		|| x > cio_textinfo.screenwidth
		|| y < 1
		|| y > cio_textinfo.screenheight)
		return;

	/* ToDo optimizations: use tabs for horizontal movement to tabstops */

	/* Movement forced... always send position code */
	if(force_move) {
		sprintf(str,"\033[%d;%dH",y,x);
		ansi_sendstr(str,-1);
		force_move=0;
		ansiy=y;
		ansix=x;
		return;
	}

	/* Moving to col 1 (and not already there)... use \r */
	if(x==1 && ansix>1) {
		ansi_sendstr("\r",1);
		ansix=1;
	}

	/* Do we even NEED to move? */
	if(x==ansix && y==ansiy)
		return;

	/* If we're already on the correct column */
	if(x==ansix) {
		/* Do we need to move up? */
		if(y<ansiy) {
			if(y==ansiy-1)
				/* Only up one */
				strcpy(str,"\033[A");
			else
				sprintf(str,"\033[%dA",ansiy-y);
			ansi_sendstr(str,-1);
			ansiy=y;
			return;
		}

		/* We must have to move down then. */
		/* Only one, use a newline */
		if(y-ansiy < 4)
			ansi_sendstr("\n\n\n",y-ansiy);
		else {
			sprintf(str,"\033[%dB",y-ansiy);
			ansi_sendstr(str,-1);
		}
		ansiy=y;
		return;
	}

	/* Ok, we need to change the column then... is the row right though? */
	if(y==ansiy) {
		/* Do we need to move left then? */
		if(x<ansix) {
			if(x==ansix-1)
				strcpy(str,"\033[D");
			else
				sprintf(str,"\033[%dD",ansix-x);
			ansi_sendstr(str,-1);
			ansix=x;
			return;
		}

		/* Must need to move right then */
#if 1
		/* Check if we can use spaces */
		if(x-ansix < 5) {
			int i,j;
			j=1;
			/* If all the intervening cells are spaces with the current background, we're good */
			for(i=0; i<x-ansix; i++) {
329
				if((ansivmem[(y-1)*cio_textinfo.screenwidth+ansix-1+i] & 0xff) != ' '/* && (ansivmem[(ansiy-1)*cio_textinfo.screenwidth+ansix-1+i]) & 0xff != 0*/) {
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
					j=0;
					break;
				}
				if((ansivmem[(y-1)*cio_textinfo.screenwidth+ansix-1+i] & 0x7000) != ((cio_textinfo.attribute<<8) & 0x7000)) {
					j=0;
					break;
				}
			}
			if(j) {
				ansi_sendstr("    ",x-ansix);
				ansix=x;
				return;
			}
		}
#endif
		if(x==ansix+1)
			strcpy(str,"\033[C");
		else
			sprintf(str,"\033[%dC",x-ansix);
		ansi_sendstr(str,-1);
		ansix=x;
		return;
352
	}
353 354 355 356 357 358 359 360 361 362 363 364 365 366

	/* Changing the row and the column... better use a fill movement then. */
	sprintf(str,"\033[%d;%dH",y,x);
	ansi_sendstr(str,-1);
	ansiy=y;
	ansix=x;
	return;
}

void ansi_gotoxy(int x, int y)
{
	ansi_gotoxy_abs(x+cio_textinfo.winleft-1,y+cio_textinfo.wintop-1);
	cio_textinfo.curx=x;
	cio_textinfo.cury=y;
367 368
}

369
int ansi_puttext(int sx, int sy, int ex, int ey, void* buf)
370 371
{
	int x,y;
372
	int cx,cy,i,j;
373 374 375 376
	unsigned char *out;
	WORD	sch;
	struct text_info	ti;
	int		attrib;
377
	unsigned char *fill = (unsigned char*)buf;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

	gettextinfo(&ti);

	if(		   sx < 1
			|| sy < 1
			|| ex < 1
			|| ey < 1
			|| sx > ti.screenwidth
			|| sy > ti.screenheight
			|| sx > ex
			|| sy > ey
			|| ex > ti.screenwidth
			|| ey > ti.screenheight
			|| fill==NULL)
		return(0);

394
	/* Check if this actually does anything */
395
	/* TODO: This assumes a little-endian system!  Ack! */
396 397
	if(sx==1 && sy==1 && ex==ti.screenwidth && ey==ti.screenheight
			&& memcmp(buf,ansivmem,ti.screenwidth*ti.screenheight*2)==0)
398
		return(1);
399

400 401
	out=fill;
	attrib=ti.attribute;
402 403 404 405 406

	i=0;		/* Did a nasty. */

	/* Check if this is a nasty screen clear... */
	j=0;		/* We can clearscreen */
407
	if(!i && sx==1 && sy==1 && ex==ti.screenwidth && ey==ti.screenheight && (*out==' ' || *out==0)) {
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
		j=1;		/* We can clearscreen */
		for(cy=sy-1;cy<ey;cy++) {
			for(cx=sx-1;cx<ex;cx++) {
				if(out[(cy*ti.screenwidth+cx)*2]!=*out
						|| out[(cy*ti.screenwidth+cx)*2+1]!=*(out+1)) {
					j=0;
					cx=ex;
					cy=ey;
				}
			}
		}
	}
	if(j) {
		textattr(*(out+1));
		/* Many terminals make ESC[2J home the cursor */
		ansi_sendstr("\033[2J\033[1;1H",-1);
424 425
		ansix=1;
		ansiy=1;
426 427 428
		memcpy(ansivmem,out,ti.screenwidth*ti.screenheight*2);
		i=1;
	}
429 430
#if 0
	/* Check if this is a scroll */
431
	if((!i) && sx==1 && sy==1 && ex==ti.screenwidth && ey==ti.screenheight-1
432 433
			&& memcmp(buf,ansivmem,ti.screenwidth*(ti.screenheight-1)*2)==0) {
		/* We need to get to the bottom line... */
434 435 436
		if(ansiy < ti.screenheight) {
			if(ansiy > ti.screenheight-4) {
				ansi_sendstr("\n\n\n\n\n",ti.screenheight-ansiy-2);
437 438
			}
			else {
439
				sprintf(str,"\033[%dB",ti.screenheight-ansiy-2);
440 441 442 443 444 445 446 447 448
				ansi_sendstr(str,-1);
			}
		}
		ansi_sendstr("\n",1);
		memcpy(ansivmem,buf,ti.screenwidth*(ti.screenheight-1)*2);
		for(x=0;x<ti.screenwidth;x++)
			ansivmem[(ti.screenheight-1)*ti.screenwidth+x]=(ti.attribute<<8)|' ';
		i=1;
	}
deuce's avatar
deuce committed
449 450
#endif
#if 1
451
	/* Check if this *includes* a scroll */
452
	if((!i) && sx==1 && sy==1 && ex==ti.screenwidth && ey==ti.screenheight
453
			&& memcmp(buf,ansivmem+ti.screenwidth,ti.screenwidth*(ti.screenheight-1)*2)==0) {
454
		/* We need to get to the bottom line... */
455 456 457
		if(ansiy < ti.screenheight) {
			if(ansiy > ti.screenheight-4) {
				ansi_sendstr("\n\n\n\n\n",ti.screenheight-ansiy-2);
458 459
			}
			else {
deuce's avatar
deuce committed
460
				char str[6];
461
				sprintf(str,"\033[%dB",ti.screenheight-ansiy-2);
462 463 464 465 466 467 468 469 470 471 472
				ansi_sendstr(str,-1);
			}
		}
		ansi_sendstr("\n",1);
		memcpy(ansivmem,buf,ti.screenwidth*(ti.screenheight-1)*2);
		for(x=0;x<ti.screenwidth;x++)
			ansivmem[(ti.screenheight-1)*ti.screenwidth+x]=(ti.attribute<<8)|' ';
		out += ti.screenwidth*(ti.screenheight-1)*2;
		sy=ti.screenheight;
	}
#endif
473 474 475 476 477 478 479 480
	if(!i) {
		for(y=sy-1;y<ey;y++) {
			for(x=sx-1;x<ex;x++) {
				/*
				 * Check if we can use clear2eol now... this means  the rest of the
				 * chars on the line are the same attr, and are all spaces or NULLs
				 * Also, if there's less than four chars left, it's not worth it.
				 */
481

482
				i=0;	/* number of differing chars from screen */
483
				j=0;	/* Can use clrtoeol? */
484
				for(cx=x; cx<ti.screenwidth; cx++) {
485
					/* First, make sure that the rest are spaces or NULLs */
486
					if(out[(cx-x)*2] != ' ' && out[(cx-x)*2] != 0)
487 488
						break;
					/* Next, make sure that the attribute is the same */
489
					if(out[(cx-x)*2+1] != out[1])
490 491
						break;
					/* Finally, if this isn't what's on screen, increment i */
492
					if((ansivmem[y*cio_textinfo.screenwidth+cx] & 0xff) != 0 && (ansivmem[y*cio_textinfo.screenwidth+cx] & 0xff) != ' ')
493
						i++;
494
					else if(ansivmem[y*cio_textinfo.screenwidth+cx] >> 8 != out[(cx-x)*2+1])
495
						i++;
496
				}
497 498 499
				if(cx==ti.screenwidth)
					j=1;

500
				if(j && i>3) {
501
					ansi_gotoxy_abs(x+1,y+1);
502 503 504
					textattr(*(out+1));
					ansi_sendstr("\033[K",-1);
					for(cx=x; cx<ex; cx++) {
505 506
						ansivmem[y*cio_textinfo.screenwidth+cx]=*(out++);
						ansivmem[y*cio_textinfo.screenwidth+cx]|=(*(out++))<<8;
507 508 509 510
					}
					break;
				}
				sch=*(out++);
511
				if(sch==27 && doorway_enabled==0)
512 513 514 515
					sch=' ';
				if(sch==0)
					sch=' ';
				sch |= (*(out++))<<8;
516
				if(ansivmem[y*cio_textinfo.screenwidth+x]==sch)
517
					continue;
518 519 520
				ansivmem[y*cio_textinfo.screenwidth+x]=sch;
				ansi_gotoxy_abs(x+1,y+1);
				if(y>=cio_textinfo.screenheight-1 && x>=cio_textinfo.screenwidth-1)
521 522 523 524 525 526
					continue;
				if(attrib!=sch>>8) {
					textattr(sch>>8);
					attrib=sch>>8;
				}
				ansi_sendch((char)(sch&0xff));
527 528 529 530
			}
		}
	}

531
	if(!puttext_can_move)
532
		gotoxy(ti.curx,ti.cury);
533 534
	if(attrib!=ti.attribute)
		textattr(ti.attribute);
deuce's avatar
deuce committed
535
	return(1);
536 537
}

538
int ansi_gettext(int sx, int sy, int ex, int ey, void* buf)
539 540 541 542 543
{
	int x,y;
	unsigned char *out;
	WORD	sch;
	struct text_info	ti;
544
	unsigned char *fill = (unsigned char*)buf;
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

	gettextinfo(&ti);

	if(		   sx < 1
			|| sy < 1
			|| ex < 1
			|| ey < 1
			|| sx > ti.screenwidth
			|| sy > ti.screenheight
			|| sx > ex
			|| sy > ey
			|| ex > ti.screenwidth
			|| ey > ti.screenheight
			|| fill==NULL)
		return(0);

	out=fill;
	for(y=sy-1;y<ey;y++) {
		for(x=sx-1;x<ex;x++) {
564
			sch=ansivmem[y*cio_textinfo.screenwidth+x];
565 566 567 568
			*(out++)=sch & 0xff;
			*(out++)=sch >> 8;
		}
	}
deuce's avatar
deuce committed
569
	return(1);
570 571
}

572
void ansi_textattr(int attr)
573 574 575 576 577 578 579 580
{
	char str[16];
	int fg,ofg;
	int bg,obg;
	int bl,obl;
	int br,obr;
	int oa;

deuce's avatar
deuce committed
581
	str[0]=0;
582
	if(cio_textinfo.attribute==attr)
deuce's avatar
deuce committed
583 584 585
		return;

	bl=attr&0x80;
586 587
	bg=(attr>>4)&0x7;
	fg=attr&0x07;
588
	br=attr&0x08;
589

590
	oa=cio_textinfo.attribute;
591
	obl=oa&0x80;
592 593
	obg=(oa>>4)&0x7;
	ofg=oa&0x07;
594
	obr=oa&0x08;
595

596
	cio_textinfo.attribute=attr;
deuce's avatar
deuce committed
597 598 599

	strcpy(str,"\033[");
	if(obl!=bl) {
600 601 602 603 604
		if(!bl)
#if 0
			strcat(str,"25;");
#else
		{
deuce's avatar
deuce committed
605 606 607 608 609
			strcat(str,"0;");
			ofg=7;
			obg=0;
			obr=0;
		}
610
#endif
deuce's avatar
deuce committed
611 612 613 614 615 616 617 618
		else
			strcat(str,"5;");
	}
	if(br!=obr) {
		if(br)
			strcat(str,"1;");
		else
#if 0
619
			strcat(str,"22;");
deuce's avatar
deuce committed
620 621 622
#else
		{
			strcat(str,"0;");
623 624
			if(bl)
				strcat(str,"5;");
deuce's avatar
deuce committed
625 626 627 628 629 630 631 632 633 634 635
			ofg=7;
			obg=0;
		}
#endif
	}
	if(fg!=ofg)
		sprintf(str+strlen(str),"3%d;",ansi_colours[fg]);
	if(bg!=obg)
		sprintf(str+strlen(str),"4%d;",ansi_colours[bg]);
	str[strlen(str)-1]='m';
	ansi_sendstr(str,-1);
636
	cio_textinfo.attribute=attr;
637 638
}

639 640 641
#if defined(__BORLANDC__)
        #pragma argsused
#endif
642 643 644
static void ansi_keyparse(void *par)
{
	int		gotesc=0;
645
	int		gotnull=0;
646 647 648 649
	char	seq[64];
	int		ch;
	int		i;
	char	*p;
deuce's avatar
deuce committed
650
	int		timeout=0;
deuce's avatar
deuce committed
651
	int		timedout=0;
deuce's avatar
deuce committed
652
	int		unknown=0;
653

deuce's avatar
deuce committed
654
	SetThreadName("ANSI Keyparse");
655
	seq[0]=0;
656
	for(;;) {
657
		if(ansi_got_row)
658
			sem_wait(&goahead);
deuce's avatar
deuce committed
659 660 661 662 663 664 665 666 667 668 669
		if(timedout || unknown) {
			for(p=seq;*p;p++) {
				ansi_inch=*p;
				sem_post(&got_input);
				sem_wait(&used_input);
				sem_wait(&goahead);
			}
			gotesc=0;
			timeout=0;
			seq[0]=0;
		}
670 671
		if(!timedout)
			sem_post(&need_key);
deuce's avatar
deuce committed
672
		timedout=0;
deuce's avatar
deuce committed
673
		unknown=0;
deuce's avatar
deuce committed
674 675
		if(timeout) {
			if(sem_trywait_block(&got_key,timeout)) {
deuce's avatar
deuce committed
676
				timedout=1;
deuce's avatar
deuce committed
677 678
				sem_post(&goahead);
				continue;
679 680
			}
		}
deuce's avatar
deuce committed
681 682
		else
			sem_wait(&got_key);
deuce's avatar
deuce committed
683 684

		ch=ansi_raw_inch;
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
		if(ch==-2) {
			ansi_inch=0x0100;
			sem_post(&got_input);
			/* Two-byte code, need to post twice times and wait for one to
			   be received */
			sem_wait(&used_input);
			sem_wait(&goahead);
			sem_post(&got_input);
			sem_wait(&used_input);
		}
		if(gotnull==2) {
			// 0xe0 enhanced keyboard key... translate to 0x00 key for now.

			ansi_inch=ch<<8;	// (ch<<8)|0xe0;
			sem_post(&got_input);
			/* Two-byte code, need to post twice times and wait for one to
			   be received */
			sem_wait(&used_input);
			sem_wait(&goahead);
			sem_post(&got_input);
			sem_wait(&used_input);
			gotnull=0;
			continue;
		}
		if(gotnull==1) {
			if(ch==0xe0) {
				gotnull=2;
				// Need another key... keep looping.
				sem_post(&goahead);
				continue;
			}
716 717 718 719 720 721 722 723 724 725 726
			ansi_inch=ch<<8;
			sem_post(&got_input);
			/* Two-byte code, need to post twice and wait for one to
			   be received */
			sem_wait(&used_input);
			sem_wait(&goahead);
			sem_post(&got_input);
			sem_wait(&used_input);
			gotnull=0;
			continue;
		}
727

728
		switch(gotesc) {
deuce's avatar
deuce committed
729
			case 1:	/* Escape Sequence */
deuce's avatar
deuce committed
730
				timeout=CIOLIB_ANSI_TIMEOUT;
deuce's avatar
deuce committed
731 732
				seq[strlen(seq)+1]=0;
				seq[strlen(seq)]=ch;
733 734 735 736 737 738 739 740 741
				if(strlen(seq)>=sizeof(seq)-2) {
					gotesc=0;
					break;
				}
				if((ch<'0' || ch>'9')		/* End of ESC sequence */
						&& ch!=';'
						&& ch!='?'
						&& (strlen(seq)==2?ch != '[':1)
						&& (strlen(seq)==2?ch != 'O':1)) {
deuce's avatar
deuce committed
742 743 744
					unknown=1;
					gotesc=0;
					timeout=0;
745 746 747
					for(i=0;ODaKeySequences[i].pszSequence[0];i++) {
						if(!strcmp(seq,ODaKeySequences[i].pszSequence)) {
							ansi_inch=ODaKeySequences[i].chExtendedKey;
deuce's avatar
deuce committed
748 749 750
							sem_post(&got_input);
							/* Two-byte code, need to post twice and wait for one to
							   be received */
751 752
							sem_wait(&used_input);
							sem_wait(&goahead);
deuce's avatar
deuce committed
753 754
							sem_post(&got_input);
							sem_wait(&used_input);
deuce's avatar
deuce committed
755 756
							unknown=0;
							seq[0]=0;
757 758 759
							break;
						}
					}
760 761 762 763 764
					/* ANSI position report? */
					if(ch=='R') {
						if(strspn(seq,"\033[0123456789;R")==strlen(seq)) {
							p=seq+2;
							i=strtol(p,&p,10);
765 766
							if(i>cio_textinfo.screenheight) {
								cio_textinfo.screenheight=i;
767 768 769 770 771 772
								if(*p==';') {
									i=strtol(p+1, NULL, 10);
									if(i>cio_textinfo.screenwidth)
										cio_textinfo.screenwidth=i;
								}
								ansi_got_row=cio_textinfo.screenheight;;
773
							}
774 775 776
						}
						unknown=0;
					}
deuce's avatar
deuce committed
777 778 779 780
					if(unknown) {
						sem_post(&goahead);
						continue;
					}
781
				}
782 783 784 785
				else {
					/* Need more keys... keep looping */
					sem_post(&goahead);
				}
786 787 788 789 790 791
				break;
			default:
				if(ch==27) {
					seq[0]=27;
					seq[1]=0;
					gotesc=1;
deuce's avatar
deuce committed
792
					timeout=CIOLIB_ANSI_TIMEOUT;
793 794
					/* Need more keys... keep going... */
					sem_post(&goahead);
795 796
					break;
				}
deuce's avatar
deuce committed
797 798
				if(ch==10) {
					/* The \n that goes with the prev \r (hopefully) */
799 800 801 802
					/* Eat it and keep chuggin' */
					sem_post(&goahead);
					break;
				}
803
				if(doorway_enabled && ch==0) {
804 805
					/* Got a NULL. ASSume this is a doorway mode char */
					gotnull=1;
deuce's avatar
deuce committed
806
					sem_post(&goahead);
807 808
					break;
				}
809
				ansi_inch=ch;
deuce's avatar
deuce committed
810
				sem_post(&got_input);
811
				sem_wait(&used_input);
812 813 814 815 816
				break;
		}
	}
}

817 818 819
#if defined(__BORLANDC__)
        #pragma argsused
#endif
820 821
static void ansi_keythread(void *params)
{
822 823
	int	sval=1;

824
	SetThreadName("ANSI Key");
825 826 827
	_beginthread(ansi_keyparse,1024,NULL);

	for(;;) {
828
		sem_wait(&need_key);
829 830
		/* If you already have a key, don't get another */
		sem_getvalue(&got_key,&sval);
831 832
		if(!sval) {
			ansi_raw_inch=ciolib_ansi_readbyte_cb();
833
			if(ansi_raw_inch >= 0 || ansi_raw_inch==-2)
834 835 836 837
				sem_post(&got_key);
			else
				SLEEP(1);
		}
838 839 840 841 842 843 844
		else
			SLEEP(1);
	}
}

int ansi_kbhit(void)
{
845
	int	sval=1;
deuce's avatar
deuce committed
846

847 848 849 850
	if(!sent_ga) {
		sem_post(&goahead);
		sent_ga=TRUE;
	}
deuce's avatar
deuce committed
851 852
	sem_getvalue(&got_input,&sval);
	return(sval);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
}

void ansi_setcursortype(int type)
{
	switch(type) {
		case _NOCURSOR:
		case _SOLIDCURSOR:
		default:
			break;
	}
}

int ansi_getch(void)
{
	int ch;

869 870 871 872
	if(!sent_ga) {
		sem_post(&goahead);
		sent_ga=TRUE;
	}
deuce's avatar
deuce committed
873
	sem_wait(&got_input);
874 875
	ch=ansi_inch&0xff;
	ansi_inch=ansi_inch>>8;
deuce's avatar
deuce committed
876
	sem_post(&used_input);
877
	sent_ga=FALSE;
878 879 880
	return(ch);
}

881
void ansi_beep(void)
882
{
883
	ansi_sendstr("\7",1);
884 885
}

886 887 888
#if defined(__BORLANDC__)
        #pragma argsused
#endif
889 890
void ansi_textmode(int mode)
{
891 892 893 894 895 896 897 898 899 900 901
	cio_textinfo.winleft=1;
	cio_textinfo.wintop=1;
	cio_textinfo.winright=cio_textinfo.screenwidth;
	cio_textinfo.winbottom=cio_textinfo.screenheight;
	cio_textinfo.attribute=7;
	cio_textinfo.normattr=7;
	cio_textinfo.currmode=COLOR_MODE;
	cio_textinfo.curx=1;
	cio_textinfo.cury=1;
	ansix=1;
	ansiy=1;
902 903 904 905 906 907 908 909 910
}

#ifdef __unix__
void ansi_fixterm(void)
{
	tcsetattr(STDIN_FILENO,TCSANOW,&tio_default);
}
#endif

deuce's avatar
deuce committed
911 912 913 914 915 916 917
#ifndef ENABLE_EXTENDED_FLAGS
#define ENABLE_INSERT_MODE		0x0020
#define ENABLE_QUICK_EDIT_MODE	0x0040
#define ENABLE_EXTENDED_FLAGS	0x0080
#define ENABLE_AUTO_POSITION	0x0100
#endif

918 919 920 921
/*
 * Returns -1 if no character read or -2 on abort
 */
int ansi_readbyte_cb(void)
922
{
923
	unsigned char ch;
deuce's avatar
deuce committed
924

925 926 927 928 929
	if(fread(&ch,1,1,stdin)!=1)
		return(-1);
	return(ch);
}

930
int ansi_writebyte_cb(const unsigned char ch)
931
{
deuce's avatar
deuce committed
932
	return(fwrite(&ch,1,1,stdout));
933 934
}

935
int ansi_writestr_cb(const unsigned char *str, size_t len)
936
{
deuce's avatar
deuce committed
937
	return(fwrite(str,len,1,stdout));
938 939 940 941
}

int ansi_initio_cb(void)
{
942
#ifdef _WIN32
Rob Swindell's avatar
Rob Swindell committed
943
	DWORD conmode = 0;
944
	if(isatty(fileno(stdin))) {
945
		if(!SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_INPUT))
946 947
			return(0);

948 949
		GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &conmode);
		if(!SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), conmode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
950 951
			return(0);
	}
952 953 954
	setmode(fileno(stdout),_O_BINARY);
	setmode(fileno(stdin),_O_BINARY);
	setvbuf(stdout, NULL, _IONBF, 0);
955 956 957 958 959 960
#else
	struct termios tio_raw;

	if (isatty(STDIN_FILENO))  {
		tcgetattr(STDIN_FILENO,&tio_default);
		tio_raw = tio_default;
deuce's avatar
deuce committed
961
		cfmakeraw(&tio_raw);
962 963 964 965 966
		tcsetattr(STDIN_FILENO,TCSANOW,&tio_raw);
		setvbuf(stdout, NULL, _IONBF, 0);
		atexit(ansi_fixterm);
	}
#endif
deuce's avatar
deuce committed
967
	return(0);
968 969 970 971 972 973 974 975 976 977 978
}

#if defined(__BORLANDC__)
        #pragma argsused
#endif
int ansi_initciolib(long inmode)
{
	int i;
	char *init="\033[s\033[99B\033[99B\033[99B_\033[99C\033[99C\033[99C_\033[6n\033[u\033[0m_\033[2J\033[H";
	time_t start;

979 980
	cio_api.options = 0;

981 982 983 984
	ansi_textmode(1);
	cio_textinfo.screenheight=24;
	cio_textinfo.screenwidth=80;
	ciolib_ansi_initio_cb();
deuce's avatar
deuce committed
985 986 987

	sem_init(&got_key,0,0);
	sem_init(&got_input,0,0);
988
	sem_init(&used_input,0,0);
989 990
	sem_init(&goahead,0,0);
	sem_init(&need_key,0,0);
deuce's avatar
deuce committed
991

992
	ansi_sendstr(init,-1);
993 994
	_beginthread(ansi_keythread,1024,NULL);
	start=time(NULL);
995
	while(time(NULL)-start < 5 && !ansi_got_row)
996
		SLEEP(1);
997 998
	if(!ansi_got_row) {
		cio_textinfo.screenheight=24;
999
		cio_textinfo.screenwidth=80;
1000 1001 1002 1003
		ansi_got_row=24;
	}
	ansivmem=(WORD *)malloc(cio_textinfo.screenheight*cio_textinfo.screenwidth*sizeof(WORD));
	for(i=0;i<cio_textinfo.screenheight*cio_textinfo.screenwidth;i++)
1004
		ansivmem[i]=0x0720;
1005 1006 1007 1008 1009 1010
	/* drain all the semaphores */
	sem_reset(&got_key);
	sem_reset(&got_input);
	sem_reset(&used_input);
	sem_reset(&goahead);
	sem_reset(&need_key);
1011
	return(1);
1012
}
1013

1014 1015
void ansi_suspend(void)
{
1016
#if defined _MSC_VER
1017 1018 1019 1020 1021
	// Prevents the wait for a key press when exit() is called and the stdin stream is flushed
	_unlock_file(stdin);
#endif
}

1022
CIOLIBEXPORT void ansi_ciolib_setdoorway(int enable)
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
{
	if(cio_api.mode!=CIOLIB_MODE_ANSI)
		return;
	switch(enable) {
	case 0:
		ansi_sendstr("\033[=255l",7);
		doorway_enabled=0;
		break;
	default:
		ansi_sendstr("\033[=255h",7);
		doorway_enabled=1;
		break;
	}
}