console.c 43.6 KB
Newer Older
Alam Ed Arias committed
1 2 3
// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1998-2000 by DooM Legacy Team.
James R. committed
4
// Copyright (C) 1999-2020 by Sonic Team Junior.
Alam Ed Arias committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file  console.c
/// \brief Console drawing and input

#ifdef __GNUC__
#include <unistd.h>
#endif

#include "doomdef.h"
#include "console.h"
#include "g_game.h"
#include "g_input.h"
#include "hu_stuff.h"
#include "keys.h"
23
#include "r_main.h"
Alam Ed Arias committed
24 25 26 27 28 29 30 31
#include "r_defs.h"
#include "sounds.h"
#include "st_stuff.h"
#include "s_sound.h"
#include "v_video.h"
#include "i_video.h"
#include "z_zone.h"
#include "i_system.h"
32
#include "i_threads.h"
Alam Ed Arias committed
33 34
#include "d_main.h"
#include "m_menu.h"
35
#include "filesrch.h"
36
#include "m_misc.h"
Alam Ed Arias committed
37 38 39 40 41 42 43 44 45 46 47

#ifdef _WINDOWS
#include "win32/win_main.h"
#endif

#ifdef HWRENDER
#include "hardware/hw_main.h"
#endif

#define MAXHUDLINES 20

48 49 50 51 52 53 54 55 56 57
#ifdef HAVE_THREADS
I_mutex con_mutex;

#  define Lock_state()    I_lock_mutex(&con_mutex)
#  define Unlock_state() I_unlock_mutex(con_mutex)
#else/*HAVE_THREADS*/
#  define Lock_state()
#  define Unlock_state()
#endif/*HAVE_THREADS*/

Alam Ed Arias committed
58
static boolean con_started = false; // console has been initialised
59 60
       boolean con_startup = false; // true at game startup
       boolean con_refresh = false; // screen needs refreshing
Alam Ed Arias committed
61 62 63 64 65 66 67 68 69 70 71 72
static boolean con_forcepic = true; // at startup toggle console translucency when first off
       boolean con_recalc;          // set true when screen size has changed

static tic_t con_tick; // console ticker for anim or blinking prompt cursor
                        // con_scrollup should use time (currenttime - lasttime)..

static boolean consoletoggle; // true when console key pushed, ticker will handle
static boolean consoleready;  // console prompt is ready

       INT32 con_destlines; // vid lines used by console at final position
static INT32 con_curlines;  // vid lines currently used by console

Jaime Ita Passos committed
73
       INT32 con_clipviewtop; // (useless)
Alam Ed Arias committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

static INT32 con_hudlines;        // number of console heads up message lines
static INT32 con_hudtime[MAXHUDLINES];      // remaining time of display for hud msg lines

       INT32 con_clearlines;      // top screen lines to refresh when view reduced
       boolean con_hudupdate;   // when messages scroll, we need a backgrnd refresh

// console text output
static char *con_line;          // console text output current line
static size_t con_cx;           // cursor position in current line
static size_t con_cy;           // cursor line number in con_buffer, is always
                                // increasing, and wrapped around in the text
                                // buffer using modulo.

static size_t con_totallines;      // lines of console text into the console buffer
static size_t con_width;           // columns of chars, depend on vid mode width

static size_t con_scrollup;        // how many rows of text to scroll up (pgup/pgdn)
UINT32 con_scalefactor;            // text size scale factor

// hold 32 last lines of input for history
#define CON_MAXPROMPTCHARS 256
96
#define CON_PROMPTCHAR '$'
Alam Ed Arias committed
97 98 99 100 101

static char inputlines[32][CON_MAXPROMPTCHARS]; // hold last 32 prompt lines

static INT32 inputline;    // current input line number
static INT32 inputhist;    // line number of history input line to restore
102 103 104 105
static size_t input_cur; // position of cursor in line
static size_t input_sel; // position of selection marker (I.E.: anything between this and input_cur is "selected")
static size_t input_len; // length of current line, used to bound cursor and such
// notice: input does NOT include the "$" at the start of the line. - 11/3/16
Alam Ed Arias committed
106 107 108 109

// protos.
static void CON_InputInit(void);
static void CON_RecalcSize(void);
110
static void CON_ChangeHeight(void);
Alam Ed Arias committed
111

Jaime Ita Passos committed
112
static void CON_DrawBackpic(void);
Alam Ed Arias committed
113
static void CONS_hudlines_Change(void);
114
static void CONS_backcolor_Change(void);
Alam Ed Arias committed
115 116 117 118 119 120 121 122 123 124 125 126 127

//======================================================================
//                   CONSOLE VARS AND COMMANDS
//======================================================================
#ifdef macintosh
#define CON_BUFFERSIZE 4096 // my compiler can't handle local vars >32k
#else
#define CON_BUFFERSIZE 16384
#endif

static char con_buffer[CON_BUFFERSIZE];

// how many seconds the hud messages lasts on the screen
128
static consvar_t cons_msgtimeout = CVAR_INIT ("con_hudtime", "5", CV_SAVE, CV_Unsigned, NULL);
Alam Ed Arias committed
129 130

// number of lines displayed on the HUD
131
static consvar_t cons_hudlines = CVAR_INIT ("con_hudlines", "5", CV_CALL|CV_SAVE, CV_Unsigned, CONS_hudlines_Change);
Alam Ed Arias committed
132 133 134 135

// number of lines console move per frame
// (con_speed needs a limit, apparently)
static CV_PossibleValue_t speed_cons_t[] = {{0, "MIN"}, {64, "MAX"}, {0, NULL}};
136
static consvar_t cons_speed = CVAR_INIT ("con_speed", "8", CV_SAVE, speed_cons_t, NULL);
Alam Ed Arias committed
137 138

// percentage of screen height to use for console
139
static consvar_t cons_height = CVAR_INIT ("con_height", "50", CV_SAVE, CV_Unsigned, NULL);
Alam Ed Arias committed
140 141 142

static CV_PossibleValue_t backpic_cons_t[] = {{0, "translucent"}, {1, "picture"}, {0, NULL}};
// whether to use console background picture, or translucent mode
143
static consvar_t cons_backpic = CVAR_INIT ("con_backpic", "translucent", CV_SAVE, backpic_cons_t, NULL);
Alam Ed Arias committed
144

145 146 147 148 149 150 151
static CV_PossibleValue_t backcolor_cons_t[] = {{0, "White"}, 		{1, "Black"},		{2, "Sepia"},
												{3, "Brown"},		{4, "Pink"},		{5, "Raspberry"},
												{6, "Red"},			{7, "Creamsicle"},	{8, "Orange"},
												{9, "Gold"},		{10,"Yellow"},		{11,"Emerald"},
												{12,"Green"},		{13,"Cyan"},		{14,"Steel"},
												{15,"Periwinkle"},	{16,"Blue"},		{17,"Purple"},
												{18,"Lavender"},
152
												{0, NULL}};
153

154

155
consvar_t cons_backcolor = CVAR_INIT ("con_backcolor", "Green", CV_CALL|CV_SAVE, backcolor_cons_t, CONS_backcolor_Change);
Alam Ed Arias committed
156 157 158 159 160 161 162 163 164

static void CON_Print(char *msg);

//
//
static void CONS_hudlines_Change(void)
{
	INT32 i;

165 166
	Lock_state();

Alam Ed Arias committed
167 168 169 170 171 172 173 174 175 176 177
	// Clear the currently displayed lines
	for (i = 0; i < con_hudlines; i++)
		con_hudtime[i] = 0;

	if (cons_hudlines.value < 1)
		cons_hudlines.value = 1;
	else if (cons_hudlines.value > MAXHUDLINES)
		cons_hudlines.value = MAXHUDLINES;

	con_hudlines = cons_hudlines.value;

178 179
	Unlock_state();

Alam Ed Arias committed
180 181 182 183 184 185 186
	CONS_Printf(M_GetText("Number of console HUD lines is now %d\n"), con_hudlines);
}

// Clear console text buffer
//
static void CONS_Clear_f(void)
{
187 188
	Lock_state();

Alam Ed Arias committed
189 190 191 192 193 194
	memset(con_buffer, 0, CON_BUFFERSIZE);

	con_cx = 0;
	con_cy = con_totallines-1;
	con_line = &con_buffer[con_cy*con_width];
	con_scrollup = 0;
195 196

	Unlock_state();
Alam Ed Arias committed
197 198 199 200
}

// Choose english keymap
//
toaster committed
201
/*static void CONS_English_f(void)
Alam Ed Arias committed
202 203 204
{
	shiftxform = english_shiftxform;
	CONS_Printf(M_GetText("%s keymap.\n"), M_GetText("English"));
toaster committed
205
}*/
Alam Ed Arias committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

static char *bindtable[NUMINPUTS];

static void CONS_Bind_f(void)
{
	size_t na;
	INT32 key;

	na = COM_Argc();

	if (na != 2 && na != 3)
	{
		CONS_Printf(M_GetText("bind <keyname> [<command>]: create shortcut keys to command(s)\n"));
		CONS_Printf("\x82%s", M_GetText("Bind table :\n"));
		na = 0;
		for (key = 0; key < NUMINPUTS; key++)
			if (bindtable[key])
			{
				CONS_Printf("%s : \"%s\"\n", G_KeynumToString(key), bindtable[key]);
				na = 1;
			}
		if (!na)
			CONS_Printf(M_GetText("(empty)\n"));
		return;
	}

	key = G_KeyStringtoNum(COM_Argv(1));
233
	if (key <= 0 || key >= NUMINPUTS)
Alam Ed Arias committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	{
		CONS_Alert(CONS_NOTICE, M_GetText("Invalid key name\n"));
		return;
	}

	Z_Free(bindtable[key]);
	bindtable[key] = NULL;

	if (na == 3)
		bindtable[key] = Z_StrDup(COM_Argv(2));
}

//======================================================================
//                          CONSOLE SETUP
//======================================================================

250 251 252
// Font colormap colors
// TODO: This could probably be improved somehow...
// These colormaps are 99% identical, with just a few changed bytes
253 254 255
// This could EASILY be handled by modifying a centralised colormap
// for software depending on the prior state - but yknow, OpenGL...
UINT8 *yellowmap, *magentamap, *lgreenmap, *bluemap, *graymap, *redmap, *orangemap, *skymap, *purplemap, *aquamap, *peridotmap, *azuremap, *brownmap, *rosymap, *invertmap;
Alam Ed Arias committed
256

257 258
// Console BG color
UINT8 *consolebgmap = NULL;
259 260
UINT8 *promptbgmap = NULL;
static UINT8 promptbgcolor = UINT8_MAX;
Alam Ed Arias committed
261

262
void CON_SetupBackColormapEx(INT32 color, boolean prompt)
Alam Ed Arias committed
263
{
264
	UINT16 i, palsum;
Marco Z committed
265
	UINT8 j, palindex;
266
	UINT8 *pal = W_CacheLumpName(GetPalette(), PU_CACHE);
267
	INT32 shift = 6;
268

269 270
	if (color == INT32_MAX)
		color = cons_backcolor.value;
271

Inuyasha committed
272
	shift = 6; // 12 colors -- shift of 7 means 6 colors
273

274
	switch (color)
275
	{
276
		case 0:		palindex = 15; 	break; 	// White
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
		case 1:		palindex = 31;	break; 	// Black
		case 2:		palindex = 251;	break;	// Sepia
		case 3:		palindex = 239;	break; 	// Brown
		case 4:		palindex = 215; shift = 7; 	break; 	// Pink
		case 5:		palindex = 37; shift = 7;	break; 	// Raspberry
		case 6:		palindex = 47; shift = 7;	break; 	// Red
		case 7:		palindex = 53;	shift = 7;	break;	// Creamsicle
		case 8:		palindex = 63;	break; 	// Orange
		case 9:		palindex = 56; shift = 7;	break; 	// Gold
		case 10:	palindex = 79; shift = 7;	break; 	// Yellow
		case 11:	palindex = 119; shift = 7; 	break; 	// Emerald
		case 12:	palindex = 111;	break; 	// Green
		case 13:	palindex = 136;	shift = 7; break; 	// Cyan
		case 14:	palindex = 175; shift = 7;	break; 	// Steel
		case 15:	palindex = 166;	shift = 7; 	break; 	// Periwinkle
		case 16:	palindex = 159;	break; 	// Blue
		case 17:	palindex = 187; shift = 7; 	break; 	// Purple
		case 18:	palindex = 199; shift = 7; 	break; 	// Lavender
295
		// Default green
296
		default:	palindex = 111; break;
297
	}
298 299 300 301 302 303 304 305 306 307 308 309 310

	if (prompt)
	{
		if (!promptbgmap)
			promptbgmap = (UINT8 *)Z_Malloc(256, PU_STATIC, NULL);

		if (color == promptbgcolor)
			return;
		else
			promptbgcolor = color;
	}
	else if (!consolebgmap)
		consolebgmap = (UINT8 *)Z_Malloc(256, PU_STATIC, NULL);
Alam Ed Arias committed
311

312 313
	// setup background colormap
	for (i = 0, j = 0; i < 768; i += 3, j++)
Alam Ed Arias committed
314
	{
Inuyasha committed
315
		palsum = (pal[i] + pal[i+1] + pal[i+2]) >> shift;
316 317 318 319
		if (prompt)
			promptbgmap[j] = (UINT8)(palindex - palsum);
		else
			consolebgmap[j] = (UINT8)(palindex - palsum);
Alam Ed Arias committed
320 321 322
	}
}

323 324 325 326 327 328
void CON_SetupBackColormap(void)
{
	CON_SetupBackColormapEx(cons_backcolor.value, false);
	CON_SetupBackColormapEx(1, true); // default to gray
}

329
static void CONS_backcolor_Change(void)
Alam Ed Arias committed
330
{
331
	CON_SetupBackColormapEx(cons_backcolor.value, false);
332
}
Alam Ed Arias committed
333

334 335 336
static void CON_SetupColormaps(void)
{
	INT32 i;
Zolton Auburn committed
337
	UINT8 *memorysrc = (UINT8 *)Z_Malloc((256*15), PU_STATIC, NULL);
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

	magentamap = memorysrc;
	yellowmap  = (magentamap+256);
	lgreenmap  = (yellowmap+256);
	bluemap    = (lgreenmap+256);
	redmap     = (bluemap+256);
	graymap    = (redmap+256);
	orangemap  = (graymap+256);
	skymap     = (orangemap+256);
	purplemap  = (skymap+256);
	aquamap    = (purplemap+256);
	peridotmap = (aquamap+256);
	azuremap   = (peridotmap+256);
	brownmap   = (azuremap+256);
	rosymap    = (brownmap+256);
	invertmap  = (rosymap+256);
Alam Ed Arias committed
354 355 356 357 358 359

	// setup the other colormaps, for console text

	// these don't need to be aligned, unless you convert the
	// V_DrawMappedPatch() into optimised asm.

360 361 362
	for (i = 0; i < (256*15); i++, ++memorysrc)
		*memorysrc = (UINT8)(i & 0xFF); // remap each color to itself...

Zolton Auburn committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
#define colset(map, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) \
	map[0x0] = (UINT8)a;\
	map[0x1] = (UINT8)b;\
	map[0x2] = (UINT8)c;\
	map[0x3] = (UINT8)d;\
	map[0x4] = (UINT8)e;\
	map[0x5] = (UINT8)f;\
	map[0x6] = (UINT8)g;\
	map[0x7] = (UINT8)h;\
	map[0x8] = (UINT8)i;\
	map[0x9] = (UINT8)j;\
	map[0xA] = (UINT8)k;\
	map[0xB] = (UINT8)l;\
	map[0xC] = (UINT8)m;\
	map[0xD] = (UINT8)n;\
	map[0xE] = (UINT8)o;\
	map[0xF] = (UINT8)p;

Zolton Auburn committed
381 382 383
	// Tried to keep the colors vanilla while adding some shades in between them ~SonicX8000

	//                      0x1       0x3                           0x9                           0xF
Zolton Auburn committed
384
	colset(magentamap, 177, 177, 178, 178, 178, 180, 180, 180, 182, 182, 182, 182, 184, 184, 184, 185);
Zolton Auburn committed
385
	colset(yellowmap,   82,  82,  73,  73,  73,  64,  64,  64,  66,  66,  66,  66,  67,  67,  67,  68);
Zolton Auburn committed
386
	colset(lgreenmap,   96,  96,  98,  98,  98, 101, 101, 101, 104, 104, 104, 104, 106, 106, 106, 107);
Zolton Auburn committed
387 388 389 390 391 392 393
	colset(bluemap,    146, 146, 147, 147, 147, 149, 149, 149, 152, 152, 152, 152, 155, 155, 155, 157);
	colset(redmap,      32,  32,  33,  33,  33,  35,  35,  35,  39,  39,  39,  39,  42,  42,  42,  44);
	colset(graymap,      8,   9,  10,  11,  12,  13,  14,  15,  16,  17,  18,  19,  20,  21,  22,  23);
	colset(orangemap,   50,  50,  52,  52,  52,  54,  54,  54,  56,  56,  56,  56,  59,  59,  59,  60);
	colset(skymap,     129, 129, 130, 130, 130, 131, 131, 131, 133, 133, 133, 133, 135, 135, 135, 136);
	colset(purplemap,  160, 160, 161, 161, 161, 162, 162, 162, 163, 163, 163, 163, 164, 164, 164, 165);
	colset(aquamap,    120, 120, 121, 121, 121, 122, 122, 122, 123, 123, 123, 123, 124, 124, 124, 125);
394
	colset(peridotmap,  72,  72, 188, 188, 189, 189, 189, 189, 190, 190, 190, 190, 191, 191, 191,  94);
Zolton Auburn committed
395 396 397
	colset(azuremap,   144, 144, 145, 145, 145, 146, 146, 146, 170, 170, 170, 170, 171, 171, 171, 172);
	colset(brownmap,   219, 219, 221, 221, 221, 222, 222, 222, 224, 224, 224, 224, 227, 227, 227, 229);
	colset(rosymap,    200, 200, 201, 201, 201, 202, 202, 202, 203, 203, 203, 203, 204, 204, 204, 205);
398 399

#undef colset
400

Zolton Auburn committed
401 402 403 404
	// Yeah just straight up invert it like a normal person
	for (i = 0x00; i <= 0x1F; i++)
		invertmap[0x1F - i] = i;

405 406
	// Init back colormap
	CON_SetupBackColormap();
Alam Ed Arias committed
407 408 409 410 411 412 413 414 415 416 417
}

// Setup the console text buffer
//
void CON_Init(void)
{
	INT32 i;

	for (i = 0; i < NUMINPUTS; i++)
		bindtable[i] = NULL;

418 419
	Lock_state();

Alam Ed Arias committed
420 421 422 423 424
	// clear all lines
	memset(con_buffer, 0, CON_BUFFERSIZE);

	// make sure it is ready for the loading screen
	con_width = 0;
425 426 427

	Unlock_state();

Alam Ed Arias committed
428 429
	CON_RecalcSize();

430
	CON_SetupColormaps();
Alam Ed Arias committed
431

432 433
	Lock_state();

Alam Ed Arias committed
434 435 436 437 438
	//note: CON_Ticker should always execute at least once before D_Display()
	con_clipviewtop = -1; // -1 does not clip

	con_hudlines = atoi(cons_hudlines.defaultvalue);

439 440
	Unlock_state();

Alam Ed Arias committed
441 442 443 444 445 446
	// setup console input filtering
	CON_InputInit();

	// register our commands
	//
	COM_AddCommand("cls", CONS_Clear_f);
toaster committed
447
	//COM_AddCommand("english", CONS_English_f);
Alam Ed Arias committed
448
	// set console full screen for game startup MAKE SURE VID_Init() done !!!
449 450
	Lock_state();

Alam Ed Arias committed
451 452 453
	con_destlines = vid.height;
	con_curlines = vid.height;

454
	Unlock_state();
Alam Ed Arias committed
455 456 457

	if (!dedicated)
	{
458 459
		Lock_state();

Alam Ed Arias committed
460
		con_started = true;
461 462
		con_startup = true;
		con_refresh = true; // needs explicit screen refresh until we are in the main game loop
Alam Ed Arias committed
463
		consoletoggle = false;
464 465 466

		Unlock_state();

Alam Ed Arias committed
467 468 469 470 471 472 473 474 475 476
		CV_RegisterVar(&cons_msgtimeout);
		CV_RegisterVar(&cons_hudlines);
		CV_RegisterVar(&cons_speed);
		CV_RegisterVar(&cons_height);
		CV_RegisterVar(&cons_backpic);
		CV_RegisterVar(&cons_backcolor);
		COM_AddCommand("bind", CONS_Bind_f);
	}
	else
	{
477 478
		Lock_state();

Alam Ed Arias committed
479
		con_started = true;
480 481
		con_startup = false;
		con_refresh = false; // disable explicit screen refresh
Alam Ed Arias committed
482
		consoletoggle = true;
483 484

		Unlock_state();
Alam Ed Arias committed
485 486 487 488 489 490
	}
}
// Console input initialization
//
static void CON_InputInit(void)
{
491 492
	Lock_state();

Alam Ed Arias committed
493 494 495
	// prepare the first prompt line
	memset(inputlines, 0, sizeof (inputlines));
	inputline = 0;
496
	input_cur = input_sel = input_len = 0;
497 498

	Unlock_state();
Alam Ed Arias committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
}

//======================================================================
//                        CONSOLE EXECUTION
//======================================================================

// Called at screen size change to set the rows and line size of the
// console text buffer.
//
static void CON_RecalcSize(void)
{
	size_t conw, oldcon_width, oldnumlines, i, oldcon_cy;
	char *tmp_buffer;
	char *string;

514 515
	Lock_state();

Alam Ed Arias committed
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
	switch (cv_constextsize.value)
	{
	case V_NOSCALEPATCH:
		con_scalefactor = 1;
		break;
	case V_SMALLSCALEPATCH:
		con_scalefactor = vid.smalldupx;
		break;
	case V_MEDSCALEPATCH:
		con_scalefactor = vid.meddupx;
		break;
	default:	// Full scaling
		con_scalefactor = vid.dupx;
		break;
	}

	con_recalc = false;

	if (dedicated)
		conw = 1;
	else
		conw = (vid.width>>3) / con_scalefactor - 2;

	if (con_curlines == vid.height) // first init
	{
		con_curlines = vid.height;
		con_destlines = vid.height;
	}

545 546 547 548 549 550
	if (con_destlines > 0) // Resize console if already open
	{
		CON_ChangeHeight();
		con_curlines = con_destlines;
	}

Alam Ed Arias committed
551 552
	// check for change of video width
	if (conw == con_width)
553 554
	{
		Unlock_state();
Alam Ed Arias committed
555
		return; // didn't change
556 557 558
	}

	Unlock_state();
Alam Ed Arias committed
559 560 561 562

	tmp_buffer = Z_Malloc(CON_BUFFERSIZE, PU_STATIC, NULL);
	string = Z_Malloc(CON_BUFFERSIZE, PU_STATIC, NULL); // BP: it is a line but who know

563 564
	Lock_state();

Alam Ed Arias committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
	oldcon_width = con_width;
	oldnumlines = con_totallines;
	oldcon_cy = con_cy;
	M_Memcpy(tmp_buffer, con_buffer, CON_BUFFERSIZE);

	if (conw < 1)
		con_width = (BASEVIDWIDTH>>3) - 2;
	else
		con_width = conw;

	con_width += 11; // Graue 06-19-2004 up to 11 control chars per line

	con_totallines = CON_BUFFERSIZE / con_width;
	memset(con_buffer, ' ', CON_BUFFERSIZE);

	con_cx = 0;
	con_cy = con_totallines-1;
	con_line = &con_buffer[con_cy*con_width];
	con_scrollup = 0;

585 586
	Unlock_state();

Alam Ed Arias committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
	// re-arrange console text buffer to keep text
	if (oldcon_width) // not the first time
	{
		for (i = oldcon_cy + 1; i < oldcon_cy + oldnumlines; i++)
		{
			if (tmp_buffer[(i%oldnumlines)*oldcon_width])
			{
				M_Memcpy(string, &tmp_buffer[(i%oldnumlines)*oldcon_width], oldcon_width);
				conw = oldcon_width - 1;
				while (string[conw] == ' ' && conw)
					conw--;
				string[conw+1] = '\n';
				string[conw+2] = '\0';
				CON_Print(string);
			}
		}
	}

	Z_Free(string);
	Z_Free(tmp_buffer);
}

609 610
static void CON_ChangeHeight(void)
{
611 612 613 614 615
	INT32 minheight;

	Lock_state();

	minheight = 20 * con_scalefactor;	// 20 = 8+8+4
616 617 618 619 620 621 622 623 624

	// toggle console in
	con_destlines = (cons_height.value*vid.height)/100;
	if (con_destlines < minheight)
		con_destlines = minheight;
	else if (con_destlines > vid.height)
		con_destlines = vid.height;

	con_destlines &= ~0x3; // multiple of text row height
625 626

	Unlock_state();
627 628
}

Alam Ed Arias committed
629 630 631 632
// Handles Console moves in/out of screen (per frame)
//
static void CON_MoveConsole(void)
{
633 634 635 636 637
	fixed_t conspeed;

	Lock_state();

	conspeed = FixedDiv(cons_speed.value*vid.fdupy, FRACUNIT);
Alam Ed Arias committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

	// instant
	if (!cons_speed.value)
	{
		con_curlines = con_destlines;
		return;
	}

	// up/down move to dest
	if (con_curlines < con_destlines)
	{
		con_curlines += FixedInt(conspeed);
		if (con_curlines > con_destlines)
			con_curlines = con_destlines;
	}
	else if (con_curlines > con_destlines)
	{
		con_curlines -= FixedInt(conspeed);
		if (con_curlines < con_destlines)
			con_curlines = con_destlines;
	}
659 660

	Unlock_state();
Alam Ed Arias committed
661 662 663 664 665 666 667 668
}

// Clear time of console heads up messages
//
void CON_ClearHUD(void)
{
	INT32 i;

669 670
	Lock_state();

Alam Ed Arias committed
671 672
	for (i = 0; i < con_hudlines; i++)
		con_hudtime[i] = 0;
673 674

	Unlock_state();
Alam Ed Arias committed
675 676 677 678 679 680
}

// Force console to move out immediately
// note: con_ticker will set consoleready false
void CON_ToggleOff(void)
{
681 682
	Lock_state();

Alam Ed Arias committed
683
	if (!con_destlines)
684 685
	{
		Unlock_state();
Alam Ed Arias committed
686
		return;
687
	}
Alam Ed Arias committed
688 689 690 691 692 693

	con_destlines = 0;
	con_curlines = 0;
	CON_ClearHUD();
	con_forcepic = 0;
	con_clipviewtop = -1; // remove console clipping of view
694 695

	I_UpdateMouseGrab();
696 697

	Unlock_state();
Alam Ed Arias committed
698 699 700 701
}

boolean CON_Ready(void)
{
702 703 704 705 706 707 708
	boolean ready;
	Lock_state();
	{
		ready = consoleready;
	}
	Unlock_state();
	return ready;
Alam Ed Arias committed
709 710 711 712 713 714 715
}

// Console ticker: handles console move in/out, cursor blinking
//
void CON_Ticker(void)
{
	INT32 i;
716 717 718 719 720
	INT32 minheight;

	Lock_state();

	minheight = 20 * con_scalefactor;	// 20 = 8+8+4
Alam Ed Arias committed
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735

	// cursor blinking
	con_tick++;
	con_tick &= 7;

	// console key was pushed
	if (consoletoggle)
	{
		consoletoggle = false;

		// toggle off console
		if (con_destlines > 0)
		{
			con_destlines = 0;
			CON_ClearHUD();
736
			I_UpdateMouseGrab();
Alam Ed Arias committed
737 738
		}
		else
739
			CON_ChangeHeight();
Alam Ed Arias committed
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
	}

	// console movement
	if (con_destlines != con_curlines)
		CON_MoveConsole();

	// clip the view, so that the part under the console is not drawn
	con_clipviewtop = -1;
	if (cons_backpic.value) // clip only when using an opaque background
	{
		if (con_curlines > 0)
			con_clipviewtop = con_curlines - viewwindowy - 1 - 10;
		// NOTE: BIG HACK::SUBTRACT 10, SO THAT WATER DON'T COPY LINES OF THE CONSOLE
		//       WINDOW!!! (draw some more lines behind the bottom of the console)
		if (con_clipviewtop < 0)
			con_clipviewtop = -1; // maybe not necessary, provided it's < 0
	}

	// check if console ready for prompt
	if (con_destlines >= minheight)
		consoleready = true;
	else
		consoleready = false;

	// make overlay messages disappear after a while
	for (i = 0; i < con_hudlines; i++)
	{
		con_hudtime[i]--;
		if (con_hudtime[i] < 0)
			con_hudtime[i] = 0;
	}
771 772

	Unlock_state();
Alam Ed Arias committed
773 774
}

775 776 777 778 779 780 781
//
// ----
//
// Shortcuts for adding and deleting characters, strings, and sections
// Necessary due to moving cursor
//

782
static void CON_InputClear(void)
783
{
784 785
	Lock_state();

786 787
	memset(inputlines[inputline], 0, CON_MAXPROMPTCHARS);
	input_cur = input_sel = input_len = 0;
788 789

	Unlock_state();
790 791
}

792
static void CON_InputSetString(const char *c)
793
{
794 795
	Lock_state();

796 797 798
	memset(inputlines[inputline], 0, CON_MAXPROMPTCHARS);
	strcpy(inputlines[inputline], c);
	input_cur = input_sel = input_len = strlen(c);
799 800

	Unlock_state();
801 802
}

803
static void CON_InputAddString(const char *c)
804 805
{
	size_t csize = strlen(c);
806 807 808

	Lock_state();

809
	if (input_len + csize > CON_MAXPROMPTCHARS-1)
810 811
	{
		Unlock_state();
812
		return;
813
	}
814 815 816 817 818
	if (input_cur != input_len)
		memmove(&inputlines[inputline][input_cur+csize], &inputlines[inputline][input_cur], input_len-input_cur);
	memcpy(&inputlines[inputline][input_cur], c, csize);
	input_len += csize;
	input_sel = (input_cur += csize);
819 820

	Unlock_state();
821 822
}

823
static void CON_InputDelSelection(void)
824 825
{
	size_t start, end, len;
826 827 828

	Lock_state();

829 830 831 832 833 834
	if (!input_cur)
	{
		Unlock_state();
		return;
	}

835 836 837 838 839 840 841 842 843 844 845 846 847
	if (input_cur > input_sel)
	{
		start = input_sel;
		end = input_cur;
	}
	else
	{
		start = input_cur;
		end = input_sel;
	}
	len = (end - start);

	if (end != input_len)
848
		memmove(&inputlines[inputline][start], &inputlines[inputline][end], input_len-end);
849 850 851 852
	memset(&inputlines[inputline][input_len - len], 0, len);

	input_len -= len;
	input_sel = input_cur = start;
853 854

	Unlock_state();
855 856
}

857
static void CON_InputAddChar(char c)
858 859 860
{
	if (input_len >= CON_MAXPROMPTCHARS-1)
		return;
861 862 863

	Lock_state();

864 865 866 867 868
	if (input_cur != input_len)
		memmove(&inputlines[inputline][input_cur+1], &inputlines[inputline][input_cur], input_len-input_cur);
	inputlines[inputline][input_cur++] = c;
	inputlines[inputline][++input_len] = 0;
	input_sel = input_cur;
869 870

	Unlock_state();
871 872
}

873
static void CON_InputDelChar(void)
874 875 876
{
	if (!input_cur)
		return;
877 878 879

	Lock_state();

880 881 882 883
	if (input_cur != input_len)
		memmove(&inputlines[inputline][input_cur-1], &inputlines[inputline][input_cur], input_len-input_cur);
	inputlines[inputline][--input_len] = 0;
	input_sel = --input_cur;
884 885

	Unlock_state();
886 887 888 889 890 891
}

//
// ----
//

Alam Ed Arias committed
892 893 894 895
// Handles console key input
//
boolean CON_Responder(event_t *ev)
{
896
	static UINT8 consdown = false; // console is treated differently due to rare usage
Alam Ed Arias committed
897 898 899 900

	// sequential completions a la 4dos
	static char completion[80];

901 902 903 904 905 906 907
	static INT32 skips;

	static INT32   com_skips;
	static INT32   var_skips;
	static INT32 alias_skips;

	const char *cmd = NULL;
Alam Ed Arias committed
908 909 910 911 912 913 914 915
	INT32 key;

	if (chat_on)
		return false;

	// let go keyup events, don't eat them
	if (ev->type != ev_keydown && ev->type != ev_console)
	{
916
		if (ev->data1 == gamecontrol[gc_console][0] || ev->data1 == gamecontrol[gc_console][1])
Alam Ed Arias committed
917 918 919 920 921 922 923 924 925
			consdown = false;
		return false;
	}

	key = ev->data1;

	// check for console toggle key
	if (ev->type != ev_console)
	{
926
		if (modeattacking || metalrecording || marathonmode)
Alam Ed Arias committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940
			return false;

		if (key == gamecontrol[gc_console][0] || key == gamecontrol[gc_console][1])
		{
			if (consdown) // ignore repeat
				return true;
			consoletoggle = true;
			consdown = true;
			return true;
		}

		// check other keys only if console prompt is active
		if (!consoleready && key < NUMINPUTS) // metzgermeister: boundary check!!
		{
941
			if (! menuactive && bindtable[key])
Alam Ed Arias committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
			{
				COM_BufAddText(bindtable[key]);
				COM_BufAddText("\n");
				return true;
			}
			return false;
		}

		// escape key toggle off console
		if (key == KEY_ESCAPE)
		{
			consoletoggle = true;
			return true;
		}
	}

958 959 960 961
	// Always eat ctrl/shift/alt if console open, so the menu doesn't get ideas
	if (key == KEY_LSHIFT || key == KEY_RSHIFT
	 || key == KEY_LCTRL || key == KEY_RCTRL
	 || key == KEY_LALT || key == KEY_RALT)
Alam Ed Arias committed
962 963
		return true;

James R. committed
964 965 966
	if (key == KEY_LEFTARROW)
	{
		if (input_cur != 0)
967 968
		{
			if (ctrldown)
969
				input_cur = M_JumpWordReverse(inputlines[inputline], input_cur);
970 971 972
			else
				--input_cur;
		}
James R. committed
973 974 975 976 977 978
		if (!shiftdown)
			input_sel = input_cur;
		return true;
	}
	else if (key == KEY_RIGHTARROW)
	{
979
		if (input_cur < input_len)
James R. committed
980
		{
981 982
			if (ctrldown)
				input_cur += M_JumpWord(&inputlines[inputline][input_cur]);
James R. committed
983 984 985 986 987 988 989 990
			else
				++input_cur;
		}
		if (!shiftdown)
			input_sel = input_cur;
		return true;
	}

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	// backspace and delete command prompt
	if (input_sel != input_cur)
	{
		if (key == KEY_BACKSPACE || key == KEY_DEL)
		{
			CON_InputDelSelection();
			return true;
		}
	}
	else if (key == KEY_BACKSPACE)
	{
		if (ctrldown)
		{
			input_sel = M_JumpWordReverse(inputlines[inputline], input_cur);
			CON_InputDelSelection();
		}
		else
			CON_InputDelChar();
		return true;
	}
	else if (key == KEY_DEL)
	{
		if (input_cur == input_len)
			return true;

		if (ctrldown)
		{
			input_sel = input_cur + M_JumpWord(&inputlines[inputline][input_cur]);
			CON_InputDelSelection();
		}
		else
		{
			++input_cur;
			CON_InputDelChar();
		}
		return true;
	}

Inuyasha committed
1029 1030
	// ctrl modifier -- changes behavior, adds shortcuts
	if (ctrldown)
Alam Ed Arias committed
1031 1032
	{
		// show all cvars/commands that match what we have inputted
Inuyasha committed
1033
		if (key == KEY_TAB)
Alam Ed Arias committed
1034
		{
1035
			size_t i, len;
Alam Ed Arias committed
1036

1037
			if (!completion[0])
Alam Ed Arias committed
1038
			{
1039 1040 1041
				if (!input_len || input_len >= 40 || strchr(inputlines[inputline], ' '))
					return true;
				strcpy(completion, inputlines[inputline]);
Alam Ed Arias committed
1042
			}
1043
			len = strlen(completion);
Alam Ed Arias committed
1044 1045 1046

			//first check commands
			CONS_Printf("\nCommands:\n");
Inuyasha committed
1047 1048 1049
			for (i = 0, cmd = COM_CompleteCommand(completion, i); cmd; cmd = COM_CompleteCommand(completion, ++i))
				CONS_Printf("  \x83" "%s" "\x80" "%s\n", completion, cmd+len);
			if (i == 0) CONS_Printf("  (none)\n");
Alam Ed Arias committed
1050 1051 1052

			//now we move on to CVARs
			CONS_Printf("Variables:\n");
Inuyasha committed
1053 1054 1055
			for (i = 0, cmd = CV_CompleteVar(completion, i); cmd; cmd = CV_CompleteVar(completion, ++i))
				CONS_Printf("  \x83" "%s" "\x80" "%s\n", completion, cmd+len);
			if (i == 0) CONS_Printf("  (none)\n");
Alam Ed Arias committed
1056

1057 1058 1059 1060 1061 1062 1063 1064
			//and finally aliases
			CONS_Printf("Aliases:\n");
			for (i = 0, cmd = COM_CompleteAlias(completion, i); cmd; cmd = COM_CompleteAlias(completion, ++i))
				CONS_Printf("  \x83" "%s" "\x80" "%s\n", completion, cmd+len);
			if (i == 0) CONS_Printf("  (none)\n");

			completion[0] = 0;

Inuyasha committed
1065 1066 1067
			return true;
		}
		// ---
Alam Ed Arias committed
1068

Inuyasha committed
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
		if (key == KEY_HOME) // oldest text in buffer
		{
			con_scrollup = (con_totallines-((con_curlines-16)>>3));
			return true;
		}
		else if (key == KEY_END) // most recent text in buffer
		{
			con_scrollup = 0;
			return true;
		}
Alam Ed Arias committed
1079

Inuyasha committed
1080 1081
		if (key == 'x' || key == 'X')
		{
1082 1083 1084 1085 1086 1087
			if (input_sel > input_cur)
				I_ClipboardCopy(&inputlines[inputline][input_cur], input_sel-input_cur);
			else
				I_ClipboardCopy(&inputlines[inputline][input_sel], input_cur-input_sel);
			CON_InputDelSelection();
			completion[0] = 0;
Inuyasha committed
1088 1089 1090 1091
			return true;
		}
		else if (key == 'c' || key == 'C')
		{
1092 1093 1094 1095
			if (input_sel > input_cur)
				I_ClipboardCopy(&inputlines[inputline][input_cur], input_sel-input_cur);
			else
				I_ClipboardCopy(&inputlines[inputline][input_sel], input_cur-input_sel);
Alam Ed Arias committed
1096 1097
			return true;
		}
Inuyasha committed
1098 1099
		else if (key == 'v' || key == 'V')
		{
1100 1101 1102 1103 1104 1105
			const char *paste = I_ClipboardPaste();
			if (input_sel != input_cur)
				CON_InputDelSelection();
			if (paste != NULL)
				CON_InputAddString(paste);
			completion[0] = 0;
Alam Ed Arias committed
1106 1107 1108
			return true;
		}

1109 1110 1111 1112 1113
		// Select all
		if (key == 'a' || key == 'A')
		{
			input_sel = 0;
			input_cur = input_len;
Inuyasha committed
1114 1115 1116
			return true;
		}

1117 1118
		// ...why shouldn't it eat the key? if it doesn't, it just means you
		// can control Sonic from the console, which is silly
Latapostrophe committed
1119
		return true;//return false;
Inuyasha committed
1120
	}
Alam Ed Arias committed
1121

Inuyasha committed
1122 1123 1124
	// command completion forward (tab) and backward (shift-tab)
	if (key == KEY_TAB)
	{
Alam Ed Arias committed
1125 1126 1127
		// sequential command completion forward and backward

		// remember typing for several completions (a-la-4dos)
1128
		if (!completion[0])
Alam Ed Arias committed
1129
		{
1130 1131 1132
			if (!input_len || input_len >= 40 || strchr(inputlines[inputline], ' '))
				return true;
			strcpy(completion, inputlines[inputline]);
1133 1134 1135 1136
			skips       = 0;
			com_skips   = 0;
			var_skips   = 0;
			alias_skips = 0;
Alam Ed Arias committed
1137 1138 1139 1140 1141
		}
		else
		{
			if (shiftdown)
			{
1142 1143
				if (skips > 0)
					skips--;
Alam Ed Arias committed
1144 1145 1146
			}
			else
			{
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
				skips++;
			}
		}

		if (skips <= com_skips)
		{
			cmd = COM_CompleteCommand(completion, skips);

			if (cmd && skips == com_skips)
			{
				com_skips  ++;
				var_skips  ++;
				alias_skips++;
			}
		}

		if (!cmd && skips <= var_skips)
		{
			cmd = CV_CompleteVar(completion, skips - com_skips);

			if (cmd && skips == var_skips)
			{
				var_skips  ++;
				alias_skips++;
Alam Ed Arias committed
1171 1172 1173
			}
		}

1174
		if (!cmd && skips <= alias_skips)
Alam Ed Arias committed
1175
		{
1176 1177 1178 1179 1180 1181
			cmd = COM_CompleteAlias(completion, skips - var_skips);

			if (cmd && skips == alias_skips)
			{
				alias_skips++;
			}
Alam Ed Arias committed
1182 1183 1184
		}

		if (cmd)
1185
		{
1186
			CON_InputSetString(va("%s ", cmd));
1187
		}
Alam Ed Arias committed
1188 1189
		else
		{
1190
			skips--;
Alam Ed Arias committed
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
		}

		return true;
	}

	// move up (backward) in console textbuffer
	if (key == KEY_PGUP)
	{
		if (con_scrollup < (con_totallines-((con_curlines-16)>>3)))
			con_scrollup++;
		return true;
	}
	else if (key == KEY_PGDN)
	{
		if (con_scrollup > 0)
			con_scrollup--;
		return true;
	}
1209
	else if (key == KEY_HOME)
Alam Ed Arias committed
1210
	{
1211 1212 1213
		input_cur = 0;
		if (!shiftdown)
			input_sel = input_cur;
Alam Ed Arias committed
1214 1215
		return true;
	}
1216
	else if (key == KEY_END)
Alam Ed Arias committed
1217
	{
1218 1219 1220
		input_cur = input_len;
		if (!shiftdown)
			input_sel = input_cur;
Alam Ed Arias committed
1221 1222 1223
		return true;
	}

1224 1225 1226
	// At this point we're messing with input
	// Clear completion
	completion[0] = 0;
Alam Ed Arias committed
1227 1228 1229 1230

	// command enter
	if (key == KEY_ENTER)
	{
1231
		if (!input_len)
Alam Ed Arias committed
1232 1233 1234
			return true;

		// push the command
1235
		COM_BufAddText(inputlines[inputline]);
Alam Ed Arias committed
1236 1237
		COM_BufAddText("\n");

1238
		CONS_Printf("\x86""%c""\x80""%s\n", CON_PROMPTCHAR, inputlines[inputline]);
Alam Ed Arias committed
1239 1240 1241

		inputline = (inputline+1) & 31;
		inputhist = inputline;
1242
		CON_InputClear();
Alam Ed Arias committed
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

		return true;
	}

	// move back in input history
	if (key == KEY_UPARROW)
	{
		// copy one of the previous inputlines to the current
		do
			inputhist = (inputhist - 1) & 31; // cycle back
1253
		while (inputhist != inputline && !inputlines[inputhist][0]);
Alam Ed Arias committed
1254 1255 1256 1257 1258 1259

		// stop at the last history input line, which is the
		// current line + 1 because we cycle through the 32 input lines
		if (inputhist == inputline)
			inputhist = (inputline + 1) & 31;

1260
		CON_InputSetString(inputlines[inputhist]);
Alam Ed Arias committed
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
		return true;
	}

	// move forward in input history
	if (key == KEY_DOWNARROW)
	{
		if (inputhist == inputline)
			return true;
		do
			inputhist = (inputhist + 1) & 31;
1271
		while (inputhist != inputline && !inputlines[inputhist][0]);
Alam Ed Arias committed
1272 1273 1274

		// back to currentline
		if (inputhist == inputline)
1275
			CON_InputClear();
Alam Ed Arias committed
1276
		else
1277
			CON_InputSetString(inputlines[inputhist]);
Alam Ed Arias committed
1278 1279 1280 1281 1282 1283
		return true;
	}

	// allow people to use keypad in console (good for typing IP addresses) - Calum
	if (key >= KEY_KEYPAD7 && key <= KEY_KPADDEL)
	{
1284 1285 1286 1287
		char keypad_translation[] = {'7','8','9','-',
		                             '4','5','6','+',
		                             '1','2','3',
		                             '0','.'};
Alam Ed Arias committed
1288 1289 1290 1291 1292 1293

		key = keypad_translation[key - KEY_KEYPAD7];
	}
	else if (key == KEY_KPADSLASH)
		key = '/';

1294 1295 1296 1297 1298 1299
	if (key >= 'a' && key <= 'z')
	{
		if (capslock ^ shiftdown)
			key = shiftxform[key];
	}
	else if (shiftdown)
Alam Ed Arias committed
1300 1301 1302 1303
		key = shiftxform[key];

	// enter a char into the command prompt
	if (key < 32 || key > 127)
Latapostrophe committed
1304
		return true;
Alam Ed Arias committed
1305 1306

	// add key to cmd line here
Latapostrophe committed
1307
	if (key >= 'A' && key <= 'Z' && !(shiftdown ^ capslock)) //this is only really necessary for dedicated servers
1308
		key = key + 'a' - 'A';
Alam Ed Arias committed
1309

1310 1311 1312
	if (input_sel != input_cur)
		CON_InputDelSelection();
	CON_InputAddChar(key);
Alam Ed Arias committed
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338

	return true;
}

// Insert a new line in the console text buffer
//
static void CON_Linefeed(void)
{
	// set time for heads up messages
	con_hudtime[con_cy%con_hudlines] = cons_msgtimeout.value*TICRATE;

	con_cy++;
	con_cx = 0;

	con_line = &con_buffer[(con_cy%con_totallines)*con_width];
	memset(con_line, ' ', con_width);

	// make sure the view borders are refreshed if hud messages scroll
	con_hudupdate = true; // see HU_Erase()
}

// Outputs text into the console text buffer
static void CON_Print(char *msg)
{
	size_t l;
	INT32 controlchars = 0; // for color changing
jameds committed
1339
	char color = '\x80';  // keep color across lines
Alam Ed Arias committed
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351

	if (msg == NULL)
		return;

	if (*msg == '\3') // chat text, makes ding sound
		S_StartSound(NULL, sfx_radio);
	else if (*msg == '\4') // chat action, dings and is in yellow
	{
		*msg = '\x82'; // yellow
		S_StartSound(NULL, sfx_radio);
	}

1352 1353
	Lock_state();

Alam Ed Arias committed
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
	if (!(*msg & 0x80))
	{
		con_line[con_cx++] = '\x80';
		controlchars = 1;
	}

	while (*msg)
	{
		// skip non-printable characters and white spaces
		while (*msg && *msg <= ' ')
		{
			if (*msg & 0x80)
			{
jameds committed
1367
				color = con_line[con_cx++] = *(msg++);
Alam Ed Arias committed
1368 1369 1370 1371 1372 1373 1374
				controlchars++;
				continue;
			}
			else if (*msg == '\r') // carriage return
			{
				con_cy--;
				CON_Linefeed();
jameds committed
1375
				color = '\x80';
Alam Ed Arias committed
1376 1377 1378 1379 1380
				controlchars = 0;
			}
			else if (*msg == '\n') // linefeed
			{
				CON_Linefeed();
jameds committed
1381 1382
				con_line[con_cx++] = color;
				controlchars = 1;
Alam Ed Arias committed
1383 1384 1385 1386 1387 1388 1389
			}
			else if (*msg == ' ') // space
			{
				con_line[con_cx++] = ' ';
				if (con_cx - controlchars >= con_width-11)
				{
					CON_Linefeed();
jameds committed
1390 1391
					con_line[con_cx++] = color;
					controlchars = 1;
Alam Ed Arias committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
				}
			}
			else if (*msg == '\t')
			{
				// adds tab spaces for nice layout in console

				do
				{
					con_line[con_cx++] = ' ';
				} while ((con_cx - controlchars) % 4 != 0);

				if (con_cx - controlchars >= con_width-11)
				{
					CON_Linefeed();
jameds committed
1406 1407
					con_line[con_cx++] = color;
					controlchars = 1;
Alam Ed Arias committed
1408 1409 1410 1411 1412 1413
				}
			}
			msg++;
		}

		if (*msg == '\0')
1414
		{
James R. committed
1415
			Unlock_state();
Alam Ed Arias committed
1416
			return;
1417
		}
Alam Ed Arias committed
1418 1419 1420 1421 1422 1423 1424 1425 1426

		// printable character
		for (l = 0; l < (con_width-11) && msg[l] > ' '; l++)
			;

		// word wrap
		if ((con_cx - controlchars) + l > con_width-11)
		{
			CON_Linefeed();
jameds committed
1427 1428
			con_line[con_cx++] = color;
			controlchars = 1;
Alam Ed Arias committed
1429 1430 1431 1432 1433 1434
		}

		// a word at a time
		for (; l > 0; l--)
			con_line[con_cx++] = *(msg++);
	}
1435 1436

	Unlock_state();
Alam Ed Arias committed
1437 1438 1439 1440
}

void CON_LogMessage(const char *msg)
{
1441
	char txt[8192], *t;
Alam Ed Arias committed
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
	const char *p = msg, *e = txt+sizeof (txt)-2;

	for (t = txt; *p != '\0'; p++)
	{
		if (*p == '\n' || *p >= ' ') // don't log or console print CON_Print's control characters
			*t++ = *p;

		if (t >= e)
		{
			*t = '\0'; //end of string
			I_OutputMsg("%s", txt); //print string
			t = txt; //reset t pointer
			memset(txt,'\0', sizeof (txt)); //reset txt
		}
	}
	*t = '\0'; //end of string
	I_OutputMsg("%s", txt);
}

// Console print! Wahooo! Lots o fun!
//

void CONS_Printf(const char *fmt, ...)
{
	va_list argptr;
	static char *txt = NULL;
1468
	boolean refresh;
Alam Ed Arias committed
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479

	if (txt == NULL)
		txt = malloc(8192);

	va_start(argptr, fmt);
	vsprintf(txt, fmt, argptr);
	va_end(argptr);

	// echo console prints to log file
	DEBFILE(txt);

SteelT committed
1480 1481
	// write message in con text buffer
	if (con_started)
Alam Ed Arias committed
1482 1483 1484 1485
		CON_Print(txt);

	CON_LogMessage(txt);

1486 1487
	Lock_state();

Alam Ed Arias committed
1488 1489
	// make sure new text is visible
	con_scrollup = 0;
1490
	refresh = con_refresh;
1491 1492

	Unlock_state();
Alam Ed Arias committed
1493 1494

	// if not in display loop, force screen update
1495
	if (refresh)
Alam Ed Arias committed
1496
	{
1497
		CON_Drawer(); // here we display the console text
Alam Ed Arias committed
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
		I_FinishUpdate(); // page flip or blit buffer
	}
}

void CONS_Alert(alerttype_t level, const char *fmt, ...)
{
	va_list argptr;
	static char *txt = NULL;

	if (txt == NULL)
		txt = malloc(8192);

	va_start(argptr, fmt);
	vsprintf(txt, fmt, argptr);
	va_end(argptr);

	switch (level)
	{
		case CONS_NOTICE:
1517
			// no notice for notices, hehe
Alam Ed Arias committed
1518 1519 1520
			CONS_Printf("\x83" "%s" "\x80 ", M_GetText("NOTICE:"));
			break;
		case CONS_WARNING:
1521
			refreshdirmenu |= REFRESHDIR_WARNING;
Alam Ed Arias committed
1522 1523 1524
			CONS_Printf("\x82" "%s" "\x80 ", M_GetText("WARNING:"));
			break;
		case CONS_ERROR:
1525
			refreshdirmenu |= REFRESHDIR_ERROR;
Alam Ed Arias committed
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
			CONS_Printf("\x85" "%s" "\x80 ", M_GetText("ERROR:"));
			break;
	}

	// I am lazy and I feel like just letting CONS_Printf take care of things.
	// Is that okay?
	CONS_Printf("%s", txt);
}

void CONS_Debug(INT32 debugflags, const char *fmt, ...)
{
	va_list argptr;
	static char *txt = NULL;

	if ((cv_debug & debugflags) != debugflags)
		return;

	if (txt == NULL)
		txt = malloc(8192);

	va_start(argptr, fmt);
	vsprintf(txt, fmt, argptr);
	va_end(argptr);

	// Again I am lazy, oh well
	CONS_Printf("%s", txt);
}


// Print an error message, and wait for ENTER key to continue.
// To make sure the user has seen the message
//
void CONS_Error(const char *msg)
{
1560
#if defined(RPC_NO_WINDOWS_H) && defined(_WINDOWS)
Alam Ed Arias committed
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
	if (!graphics_started)
	{
		MessageBoxA(vid.WndParent, msg, "SRB2 Warning", MB_OK);
		return;
	}
#endif
	CONS_Printf("\x82%s", msg); // write error msg in different colour
	CONS_Printf(M_GetText("Press ENTER to continue\n"));

	// dirty quick hack, but for the good cause
	while (I_GetKey() != KEY_ENTER)
		I_OsPolling();
}

//======================================================================
//                          CONSOLE DRAW
//======================================================================

// draw console prompt line
//
static void CON_DrawInput(void)
{
	INT32 charwidth = (INT32)con_scalefactor << 3;
1584 1585 1586 1587
	const char *p = inputlines[inputline];
	size_t c, clen, cend;
	UINT8 lellip = 0, rellip = 0;
	INT32 x, y, i;
Alam Ed Arias committed
1588 1589

	y = con_curlines - 12 * con_scalefactor;
1590
	x = charwidth*2;
Alam Ed Arias committed
1591

1592
	clen = con_width-13;
Alam Ed Arias committed
1593

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
	if (input_len <= clen)
	{
		c = 0;
		clen = input_len;
	}
	else // input line scrolls left if it gets too long
	{
		clen -= 2; // There will always be some extra truncation -- but where is what we'll find out

		if (input_cur <= clen/2)
		{
			// Close enough to right edge to show all
			c = 0;
			// Always will truncate right side from this position, so always draw right ellipsis
			rellip = 1;
		}
		else
		{
			// Cursor in the middle (or right side) of input
			// Move over for the ellipsis
			c = input_cur - (clen/2) + 2;
			x += charwidth*2;
			lellip = 1;

			if (c + clen >= input_len)
			{
				// Cursor in the right side of input
				// We were too far over, so move back
				c = input_len - clen;
			}
			else
			{
				// Cursor in the middle -- ellipses on both sides
				clen -= 2;
				rellip = 1;
			}
		}
	}

	if (lellip)
	{
1635 1636
		x -= charwidth*3;
		if (input_sel < c)
Inuyasha committed
1637
			V_DrawFill(x, y, charwidth*3, (10 * con_scalefactor), 77 | V_NOSCALESTART);
1638
		for (i = 0; i < 3; ++i, x += charwidth)
1639
			V_DrawCharacter(x, y, '.' | cv_constextsize.value | V_GRAYMAP | V_NOSCALESTART, true);
1640 1641
	}
	else
1642
		V_DrawCharacter(x-charwidth, y, CON_PROMPTCHAR | cv_constextsize.value | V_GRAYMAP | V_NOSCALESTART, true);
1643 1644 1645 1646 1647

	for (cend = c + clen; c < cend; ++c, x += charwidth)
	{
		if ((input_sel > c && input_cur <= c) || (input_sel <= c && input_cur > c))
		{
Inuyasha committed
1648
			V_DrawFill(x, y, charwidth, (10 * con_scalefactor), 77 | V_NOSCALESTART);
1649
			V_DrawCharacter(x, y, p[c] | cv_constextsize.value | V_YELLOWMAP | V_NOSCALESTART, true);
1650 1651
		}
		else
1652
			V_DrawCharacter(x, y, p[c] | cv_constextsize.value | V_NOSCALESTART, true);
1653 1654

		if (c == input_cur && con_tick >= 4)
1655
			V_DrawCharacter(x, y + (con_scalefactor*2), '_' | cv_constextsize.value | V_NOSCALESTART, true);
1656 1657
	}
	if (cend == input_cur && con_tick >= 4)
1658
		V_DrawCharacter(x, y + (con_scalefactor*2), '_' | cv_constextsize.value | V_NOSCALESTART, true);
1659 1660
	if (rellip)
	{
1661
		if (input_sel > cend)
Inuyasha committed
1662
			V_DrawFill(x, y, charwidth*3, (10 * con_scalefactor), 77 | V_NOSCALESTART);
1663
		for (i = 0; i < 3; ++i, x += charwidth)
1664
			V_DrawCharacter(x, y, '.' | cv_constextsize.value | V_GRAYMAP | V_NOSCALESTART, true);
1665
	}
Alam Ed Arias committed
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
}

// draw the last lines of console text to the top of the screen
static void CON_DrawHudlines(void)
{
	UINT8 *p;
	size_t i;
	INT32 y;
	INT32 charflags = 0;
	INT32 charwidth = 8 * con_scalefactor;
	INT32 charheight = 8 * con_scalefactor;

	if (con_hudlines <= 0)
		return;

Latapostrophe committed
1681
	if (chat_on && OLDCHAT)
Latapostrophe committed
1682
		y = charheight; // leave place for chat input in the first row of text (only do it if consolechat is on.)
Alam Ed Arias committed
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
	else
		y = 0;

	for (i = con_cy - con_hudlines+1; i <= con_cy; i++)
	{
		size_t c;
		INT32 x;

		if ((signed)i < 0)
			continue;
		if (con_hudtime[i%con_hudlines] == 0)
			continue;

		p = (UINT8 *)&con_buffer[(i%con_totallines)*con_width];

		for (c = 0, x = 0; c < con_width; c++, x += charwidth, p++)
		{
			while (*p & 0x80) // Graue 06-19-2004
			{
				charflags = (*p & 0x7f) << V_CHARCOLORSHIFT;
				p++;
			}
			if (*p < HU_FONTSTART)
				;//charwidth = 4 * con_scalefactor;
			else
			{
1709
				//charwidth = (hu_font['A'-HU_FONTSTART]->width) * con_scalefactor;
1710
				V_DrawCharacter(x, y, (INT32)(*p) | charflags | cv_constextsize.value | V_NOSCALESTART, true);
Alam Ed Arias committed
1711 1712 1713
			}
		}

1714
		//V_DrawCharacter(x, y, (p[c]&0xff) | cv_constextsize.value | V_NOSCALESTART, true);
Alam Ed Arias committed
1715 1716 1717 1718 1719 1720 1721
		y += charheight;
	}

	// top screen lines that might need clearing when view is reduced
	con_clearlines = y; // this is handled by HU_Erase();
}

Jaime Ita Passos committed
1722 1723 1724 1725 1726 1727 1728
// Lactozilla: Draws the console's background picture.
static void CON_DrawBackpic(void)
{
	patch_t *con_backpic;
	lumpnum_t piclump;
	int x, w, h;

1729 1730