sources/interface.cpp

Mon, 11 Jan 2016 02:59:18 +0200

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Mon, 11 Jan 2016 02:59:18 +0200
changeset 120
32ba3ae4daf1
parent 119
9eb47f1899be
child 126
6a0d6bddf2ab
permissions
-rw-r--r--

Fixed missing newline in /connect usage message

/*
	Copyright 2014 - 2016 Teemu Piippo
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

	1. Redistributions of source code must retain the above copyright
	   notice, this list of conditions and the following disclaimer.
	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.
	3. Neither the name of the copyright holder nor the names of its
	   contributors may be used to endorse or promote products derived from
	   this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
	TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
	PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
	OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
	PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <curses.h>
#include <string.h>
#include <time.h>
#include "interface.h"
#include "network/rconsession.h"
#include "network/ipaddress.h"
#include "coloredline.h"
BEGIN_ZFC_NAMESPACE

static const int g_pageSize = 10;

// -------------------------------------------------------------------------------------------------
//
chtype Interface::color_pair (Color fg, Color bg)
{
	if (fg == DEFAULT && bg == DEFAULT)
		return 0;
	else
		return COLOR_PAIR (1 + (int (fg) * NUM_COLORS) + int (bg));
}

// -------------------------------------------------------------------------------------------------
//
const String& Interface::current_input()
{
	return InputHistory[InputCursor];
}

// -------------------------------------------------------------------------------------------------
//
// Makes current_input() the lastmost input (so that we won't modify history)
//
void Interface::detach_input()
{
	if (InputCursor > 0)
	{
		InputHistory[0] = current_input();
		InputCursor = 0;
	}
}

// -------------------------------------------------------------------------------------------------
// A version of current_input() that allows changing the contents of it.
//
String& Interface::mutable_current_input()
{
	detach_input();
	return InputHistory[InputCursor];
}

// -------------------------------------------------------------------------------------------------
//
void Interface::move_input_cursor (int delta)
{
	// No input history when inputting addresses or passwords
	if (CurrentInputState != INPUTSTATE_NORMAL)
	{
		InputCursor = 0;
		return;
	}

	int oldcursor = InputCursor;
	InputCursor = clamp (InputCursor + delta, 0, InputHistory.size() - 1);

	if (InputCursor != oldcursor)
	{
		CursorPosition = current_input().length();
		NeedInputRender = true;
	}
}

// -------------------------------------------------------------------------------------------------
//
String Interface::prompt_string()
{
	String prompt;

	switch (CurrentInputState)
	{
	case INPUTSTATE_NORMAL: prompt = ">"; break;
	case INPUTSTATE_ADDRESS: prompt = "address:"; break;
	case INPUTSTATE_PASSWORD: prompt = "password:"; break;
	case INPUTSTATE_CONFIRM_DISCONNECTION: break;
	}

	return prompt;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::set_input_state (InputState newstate)
{
	// Clear the input row (unless going to or from confirm state)
	if (newstate != INPUTSTATE_CONFIRM_DISCONNECTION
		and CurrentInputState != INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		InputCursor = 0;
		mutable_current_input().clear();
	}

	switch (newstate)
	{
	case INPUTSTATE_ADDRESS:
		if (CurrentAddress.host != 0)
			mutable_current_input() = CurrentAddress.to_string (IPAddress::WITH_PORT);
		break;

	default:
		break;
	}

	CurrentInputState = newstate;
	NeedInputRender = true;
}

// -------------------------------------------------------------------------------------------------
//
Interface::Interface() :
	InputCursor (0),
	CursorPosition (0),
	InputPanning (0),
	NeedRefresh (false),
	NeedStatusBarRender (false),
	NeedInputRender (false),
	NeedOutputRender (false),
	NeedNicklistRender (false),
	OutputScroll (0),
	CurrentInputState (INPUTSTATE_NORMAL),
	DisconnectConfirmFunction (nullptr)
{
	::initscr();
	::raw();
	::keypad (stdscr, true);
	::noecho();
	::refresh();
	::timeout (0);
	InputHistory.clear();
	InputHistory << "";
	OutputLines.clear();
	OutputLines << ColoredLine();
	Session.set_interface (this);
	reset_title();

	if (::has_colors())
	{
		::start_color();
		bool hasDefaultColors = (::use_default_colors() == OK);
		int defaultFg = hasDefaultColors ? -1 : COLOR_WHITE;
		int defaultBg = hasDefaultColors ? -1 : COLOR_BLACK;

		// Initialize color pairs
		for (int i = 0; i < NUM_COLORS; ++i)
		for (int j = 0; j < NUM_COLORS; ++j)
		{
			int pairnum = 1 + (i * NUM_COLORS + j);
			int fg = (i == DEFAULT) ? defaultFg : i;
			int bg = (j == DEFAULT) ? defaultBg : j;

			if (fg != -1 || bg != -1)
			{
				if (::init_pair (pairnum, fg, bg) == ERR)
					print_warning ("Unable to initialize color pair %d (%d, %d)\n", pairnum, fg, bg);
			}
		}
	}

	render_full();
	refresh();
	NeedRefresh = false;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render_titlebar()
{
	if (Title.length() <= COLS)
	{
		chtype pair = color_pair (WHITE, BLUE);
		int startx = (COLS - Title.length()) / 2;
		int endx = startx + Title.length();
		attron (pair);
		mvprintw (0, startx, "%s", Title.chars());
		mvhline (0, 0, ' ', startx);
		mvhline (0, endx, ' ', COLS - endx);
		attroff (pair);
	}

	NeedRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::set_title (const String& title)
{
	Title = title;
	render_titlebar();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::safe_disconnect (std::function<void(bool)> afterwards)
{
	if (Session.is_active())
	{
		DisconnectConfirmFunction = afterwards;
		set_input_state (INPUTSTATE_CONFIRM_DISCONNECTION);
	}
	else
		afterwards(false);
}

// -------------------------------------------------------------------------------------------------
//
int Interface::nicklist_width()
{
	// Allocate at least 12 characters, at most 24 characters, for the nicklist. If we cannot
	// afford that (o_O) then we probably shouldn't draw the nicklist at all I think.
	int nicklistWidth = COLS / 4;

	if (nicklistWidth < 12)
		return 0;

	return min (nicklistWidth, 24);
}

// -------------------------------------------------------------------------------------------------
// Renders the given colored line onto the screen. Will wrap if allowWrap is true. Returns the
// 'y' value for the next line.
//
int Interface::render_colorline (int y, int x0, int width, const ColoredLine& line, bool allowWrap)
{
	int x = x0;

	for (int i = 0; i < line.data().size(); ++i)
	{
		int byte = line.data()[i];

		if (x == x0 + width)
		{
			if (not allowWrap)
				return y;

			x = x0;
			++y;
		}

		if (byte < 256 && isprint (byte))
		{
			mvaddch (y, x, char (byte));
			++x;
		}
		else if (byte >= RLINE_ON_COLOR and byte < (RLINE_ON_COLOR + 16))
		{
			auto attrfunction = (byte < RLINE_OFF_COLOR ? &attron : &attroff);
			(*attrfunction) (color_pair (Color ((byte - RLINE_ON_COLOR) & 7), DEFAULT));
		}
		else switch (byte)
		{
		case RLINE_ON_BOLD:
			attron (A_BOLD);
			break;

		case RLINE_OFF_BOLD:
			attroff (A_BOLD);
			break;
		}
	}

	return y + 1;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render_output()
{
	if (OutputLines.size() == 1)
		return;

	OutputScroll = clamp (OutputScroll, 0, OutputLines.size() - 1);

	int height = LINES - 3;
	int width = COLS - nicklist_width();
	int printOffset = 0;
	int end = OutputLines.size() - 1 - OutputScroll;
	int start = end;
	int usedHeight = 0;
	int y = 1;
	bool tightFit = false;

	// Where to start?
	while (start > 0)
	{
		int rows = OutputLines[start - 1].rows (width);

		if (usedHeight + rows > height)
		{
			// This line won't fit anymore.
			tightFit = true;
			break;
		}

		start--;
		usedHeight += rows;
	}

	// See if there's any more rows to use (end may be too small)
	if (not tightFit)
	{
		while (end < OutputLines.size())
		{
			int rows = OutputLines[end].rows (width);

			if (usedHeight + rows > height)
			{
				tightFit = true;
				break;
			}

			end++;
			usedHeight += rows;
		}
	}

	if (start > 0)
		printOffset = height - usedHeight;

	OutputScroll = OutputLines.size() - 1 - end;

	if (start < 0 or start == end or printOffset >= height)
		return;

	assert (start <= end and start - end <= height);

	// Clear the display
	for (int i = y; i < y + height; ++i)
		mvhline (i, 0, ' ', width);

	// Print the lines
	y += printOffset;

	for (int i = start; i < end; ++i)
		y = render_colorline (y, 0, width, OutputLines[i], true);

	NeedOutputRender = false;
	NeedRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render_nicklist()
{
	int width = nicklist_width();
	int height = LINES- 3;
	int y = 1;
	int x = COLS - width;

	if (width == 0)
		return;

	for (int i = 0; i < height; ++i)
	{
		mvhline (y, x, ' ', width);

		if (i < PlayerNames.size())
		{
			String displaynick = PlayerNames[i];

			if (displaynick.length() > width)
			{
				displaynick = displaynick.mid (0, width - 3);
				displaynick += "...";
			}

			mvprintw (y, x, "%s", displaynick.chars());
		}

		y++;
	}

	NeedNicklistRender = false;
	NeedRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render_input()
{
	chtype promptColor = color_pair (WHITE, BLUE);

	// If we're asking the user if they want to disconnect, we don't render any input strings,
	// just the confirmation message.
	if (CurrentInputState == INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		attron (promptColor);
		mvhline (LINES - 2, 0, ' ', COLS);
		mvprintw (LINES - 2, 0, "Are you sure you want to disconnect? y/n");
		attroff (promptColor);
		NeedRefresh = true;
		return;
	}

	String prompt = prompt_string();
	int displayLength = COLS - prompt.length() - 2;
	String displayString = current_input();
	int y = LINES - 2;

	// If we're inputting a password, replace it with asterisks
	if (CurrentInputState == INPUTSTATE_PASSWORD)
	{
		for (int i = 0; i < displayString.length(); ++i)
			displayString[i] = '*';
	}

	// Ensure the cursor is within bounds
	CursorPosition = clamp (CursorPosition, 0, displayString.length());

	// Ensure that the cursor is always in view, adjust panning if this is not the case
	if (CursorPosition > InputPanning + displayLength)
		InputPanning = CursorPosition - displayLength; // cursor went too far right
	else if (CursorPosition < InputPanning)
		InputPanning = CursorPosition; // cursor went past the pan value to the left

	// What part of the string to draw?
	int start = InputPanning;
	int end = min<int> (displayString.length(), start + displayLength);
	assert (CursorPosition >= start and CursorPosition <= end);

	// Render the input string
	mvhline (LINES - 2, 0, ' ', COLS);
	mvprintw (y, prompt.length() + 1, "%s", displayString.mid (start, end).chars());

	// Render the prompt
	attron (promptColor);
	mvprintw (y, 0, "%s", prompt.chars());
	attroff (promptColor);

	// Store in memory where the cursor is now (so that we can re-draw it to position the terminal
	// cursor).
	CursorCharacter.ch = CursorPosition != 0 ? displayString[CursorPosition - 1] : '\0';
	CursorCharacter.x = prompt.length() + (CursorPosition - InputPanning);
	NeedRefresh = true;
	NeedInputRender = false;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render_statusbar()
{
	chtype color = color_pair (WHITE, BLUE);
	int y = LINES - 1;
	attron (color);
	mvhline (y, 0, ' ', COLS);
	mvprintw (y, 0, "%s", StatusBarText.chars());
	attroff (color);
	NeedRefresh = true;
	NeedStatusBarRender = false;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::update_statusbar()
{
	String text;

	switch (Session.state())
	{
	case RCON_DISCONNECTED:
		text = "Disconnected.";
		break;

	case RCON_CONNECTING:
	case RCON_AUTHENTICATING:
		text = "Connecting to " + Session.address().to_string (IPAddress::WITH_PORT) + "...";
		break;

	case RCON_CONNECTED:
		{
			String adminText;

			if (Session.num_admins() == 0)
			{
				adminText = "No other admins";
			}
			else
			{
				adminText.sprintf ("%d other admin%s", Session.num_admins(),
					Session.num_admins() != 1 ? "s" : "");
			}

			text.sprintf ("%s | %s | %s",
				Session.address().to_string (IPAddress::WITH_PORT).chars(),
				Session.level().chars(),
				adminText.chars());
		}
		break;
	}

	if (not text.is_empty())
		text += " | ";

	text += "Ctrl+N to connect, Ctrl+Q to ";
	text += (Session.state() == RCON_DISCONNECTED) ? "quit" : "disconnect";

	if (text != StatusBarText)
	{
		StatusBarText = text;
		NeedStatusBarRender = true;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render_full()
{
	update_statusbar();
	render_titlebar();
	render_output();
	render_statusbar();
	render_input();
	render_nicklist();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::position_cursor()
{
	// This is only relevant if the input string is being drawn
	if (CurrentInputState == INPUTSTATE_CONFIRM_DISCONNECTION)
		return;

	int y = LINES - 2;

	if (CursorCharacter.ch != '\0')
		mvprintw (y, CursorCharacter.x, "%c", CursorCharacter.ch);
	else
		mvprintw (y, prompt_string().length(), " ");
}

// -------------------------------------------------------------------------------------------------
//
int Interface::find_previous_word()
{
	const String& input = current_input();
	int pos = CursorPosition;

	// Move past whitespace
	while (pos > 0 and isspace (input[pos - 1]))
		pos--;

	// Move past the word
	while (pos > 0 and not isspace (input[pos - 1]))
		pos--;

	return pos;
}

// -------------------------------------------------------------------------------------------------
//
int Interface::find_next_word()
{
	const String& input = current_input();
	int pos = CursorPosition;

	// Move past current whitespace
	while (pos < input.length() and isspace (input[pos]))
		pos++;

	// Move past the word
	while (input[pos] != '\0' and not isspace (input[pos]))
		pos++;

	return pos;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::yank (int a, int b)
{
	if (a >= b)
		return;

	if (CursorPosition > a and CursorPosition <= b)
		CursorPosition = a;

	String& input = mutable_current_input();
	PasteBuffer = input.mid (a, b);
	input.remove (a, b - a);
	NeedInputRender = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::handle_input()
{
	int ch = ::getch();

	if (ch < 0)
		return;

	if (ch == KEY_RESIZE)
	{
		::clear();
		render_full();
		return;
	}

	if (CurrentInputState == INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		if (ch == 'y' or ch == 'Y')
		{
			Session.disconnect();
			DisconnectConfirmFunction(true);
		}
		else if (ch == 'n' or ch == 'N')
			set_input_state (INPUTSTATE_NORMAL);

		return;
	}

	if (ch >= 0x20 and ch <= 0x7E)
	{
		mutable_current_input().insert (CursorPosition++, char (ch));
		NeedInputRender = true;
	}
	else switch (ch)
	{
	case 'Q' - 'A' + 1: // ^Q
		switch (CurrentInputState)
		{
		case INPUTSTATE_CONFIRM_DISCONNECTION:
			break;

		case INPUTSTATE_NORMAL:
			safe_disconnect ([&](bool hadsession)
			{
				if (hadsession)
				{
					set_input_state (INPUTSTATE_NORMAL);
				}
				else
				{
					endwin();
					throw Exitception();
				}
			});
			break;

		case INPUTSTATE_PASSWORD:
			set_input_state (INPUTSTATE_ADDRESS);
			break;

		case INPUTSTATE_ADDRESS:
			set_input_state (INPUTSTATE_NORMAL);
		}
		break;

	case KEY_LEFT:
	case 'B' - 'A' + 1: // readline ^B
		if (CursorPosition > 0)
		{
			CursorPosition--;
			NeedInputRender = true;
		}
		break;

	case KEY_RIGHT:
	case 'F' - 'A' + 1: // readline ^F
		if (CursorPosition < current_input().length())
		{
			CursorPosition++;
			NeedInputRender = true;
		}
		break;

	case KEY_DOWN:
	case KEY_UP:
		move_input_cursor (ch == KEY_DOWN ? -1 : 1);
		break;

	case KEY_HOME:
	case 'A' - 'A' + 1: // readline ^A
		if (CursorPosition != 0)
		{
			CursorPosition = 0;
			NeedInputRender = true;
		}
		break;

	case KEY_END:
	case 'E' - 'A' + 1: // readline ^E
		if (CursorPosition != current_input().length())
		{
			CursorPosition = current_input().length();
			NeedInputRender = true;
		}
		break;

	case KEY_BACKSPACE:
	case '\b':
		if (CursorPosition > 0)
		{
			mutable_current_input().remove_at (--CursorPosition);
			NeedInputRender = true;
		}
		break;

	case KEY_DC:
	case 'D' - 'A' + 1: // readline ^D
		if (CursorPosition < current_input().length())
		{
			mutable_current_input().remove_at (CursorPosition);
			NeedInputRender = true;
		}
		break;

	case KEY_PPAGE:
		OutputScroll += min (g_pageSize, LINES / 2);
		NeedOutputRender = true;
		break;

	case KEY_NPAGE:
		OutputScroll -= min (g_pageSize, LINES / 2);
		NeedOutputRender = true;
		break;

	case 'U' - 'A' + 1: // readline ^U - delete from start to cursor
		if (CursorPosition > 0)
		{
			yank (0, CursorPosition);
			CursorPosition = 0;
		}
		break;

	case 'K' - 'A' + 1: // readline ^K - delete from cursor to end
		yank (CursorPosition, mutable_current_input().length());
		break;

	case 'W' - 'A' + 1: // readline ^W - delete from previous word bounary to current
		yank (find_previous_word(), CursorPosition);
		break;

	case 'Y' - 'A' + 1: // readline ^Y - paste previously deleted text
		if (not PasteBuffer.is_empty())
		{
			mutable_current_input().insert (CursorPosition, PasteBuffer);
			CursorPosition += PasteBuffer.length();
			NeedInputRender = true;
		}
		break;

	case '\t':
		{
			int space = current_input().find (" ");

			if (CurrentInputState == INPUTSTATE_NORMAL
				and CursorPosition > 0
				and (space == -1 or space >= CursorPosition))
			{
				String start = current_input().mid (0, CursorPosition);
				Session.request_tab_complete (start);
			}
		}
		break;

	case '\n':
	case '\r':
	case KEY_ENTER:
		switch (CurrentInputState)
		{
		case INPUTSTATE_CONFIRM_DISCONNECTION:
			break; // handled above

		case INPUTSTATE_ADDRESS:
			try
			{
				CurrentAddress = IPAddress::from_string (current_input());
			}
			catch (std::exception& e)
			{
				print ("%s\n", e.what());
				return;
			}

			if (CurrentAddress.port == 0)
				CurrentAddress.port = 10666;

			set_input_state (INPUTSTATE_PASSWORD);
			break;

		case INPUTSTATE_PASSWORD:
			if (CurrentInputState == INPUTSTATE_PASSWORD and not current_input().is_empty())
			{
				Session.disconnect();
				Session.set_password (current_input());
				Session.connect (CurrentAddress);
				set_input_state (INPUTSTATE_NORMAL);
			}
			break;

		case INPUTSTATE_NORMAL:
			if (current_input()[0] == '/')
			{
				handle_command(current_input());
				flush_input();
			}
			else if (Session.send_command (current_input()))
			{
				flush_input();
			}
			break;
		}
		break;

	case 'N' - 'A' + 1: // ^N
		if (CurrentInputState == INPUTSTATE_NORMAL)
			safe_disconnect ([&](bool){set_input_state (INPUTSTATE_ADDRESS);});
		break;

	case '\x1b': // Escape
		// We may have an alt key coming
		ch = ::getch();

		if (ch != ERR)
		{
			switch (ch)
			{
			case 'b':
			case 'B':
				// readline alt-b - move one word to the left
				CursorPosition = find_previous_word();
				NeedInputRender = true;
				break;

			case 'f':
			case 'F':
				// readline alt-f - move one word to the right
				CursorPosition = find_next_word();
				NeedInputRender = true;
				break;

			case 'd':
			case 'D':
				// readline alt-d - delete from here till next word boundary
				yank (CursorPosition, find_next_word());
				break;

			case KEY_BACKSPACE: // alt+backspace, remove previous word
			case '\b':
				yank (find_previous_word(), CursorPosition);
				break;
			}
		}
		else
		{
			// No alt-key, handle pure escape
			if (CurrentInputState == INPUTSTATE_PASSWORD)
				set_input_state (INPUTSTATE_ADDRESS);
			else if (CurrentInputState == INPUTSTATE_ADDRESS)
				set_input_state (INPUTSTATE_NORMAL);
		}
		break;
	}

	render();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render()
{
	if (NeedStatusBarRender) render_statusbar();
	if (NeedInputRender) render_input();
	if (NeedOutputRender) render_output();
	if (NeedNicklistRender) render_nicklist();

	if (NeedRefresh)
	{
		position_cursor();
		refresh();
		NeedRefresh = false;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::vprint (const char* fmtstr, va_list args)
{
	String message;
	message.vsprintf (fmtstr, args);
	print_to_console (message);
}

// -------------------------------------------------------------------------------------------------
//
void __cdecl Interface::print_text (const char* fmtstr, ...)
{
	va_list args;
	va_start (args, fmtstr);
	vprint (fmtstr, args);
	va_end (args);
}

// -------------------------------------------------------------------------------------------------
//
void __cdecl Interface::print (const char* fmtstr, ...)
{
	va_list args;
	va_start (args, fmtstr);
	print_to_console (TEXTCOLOR_BrightBlue);
	vprint (fmtstr, args);
	va_end (args);
}

// -------------------------------------------------------------------------------------------------
//
void __cdecl Interface::print_warning (const char* fmtstr, ...)
{
	va_list args;
	va_start (args, fmtstr);
	print_to_console (TEXTCOLOR_BrightYellow "-!- ");
	vprint (fmtstr, args);
	va_end (args);
}

// -------------------------------------------------------------------------------------------------
//
void __cdecl Interface::print_error (const char* fmtstr, ...)
{
	va_list args;
	va_start (args, fmtstr);
	print_to_console (TEXTCOLOR_BrightRed "!!! ");
	vprint (fmtstr, args);
	va_end (args);
}

// -------------------------------------------------------------------------------------------------
//
void Interface::print_to_console (String message)
{
	// Zandronum sometimes sends color codes as "\\c" and sometimes as "\x1C".
	// Let's correct that on our end and hope this won't cause conflicts.
	message.replace ("\\c", "\x1C");

	for (int i = 0; i < message.length(); ++i)
	{
		char ch = message[i];

		if (ch == '\n')
		{
			OutputLines.last().finalize();
			OutputLines << ColoredLine();
			continue;
		}

		if (OutputLines.last().length() == 0)
		{
			time_t now;
			time (&now);
			char timestamp[32];
			strftime (timestamp, sizeof timestamp, "[%H:%M:%S] ", localtime (&now));

			for (char* cp = timestamp; *cp != '\0'; ++cp)
				OutputLines.last().add_char (*cp);
		}

		// Remove some lines if there's too many of them. 20,000 should be enough, I hope.
		while (OutputLines.size() > 20000)
			OutputLines.remove_at(0);

		OutputLines.last().add_char (ch);
	}

	NeedOutputRender = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::connect (String address, String password)
{
	try
	{
		CurrentAddress = IPAddress::from_string (address);
	}
	catch (std::exception& e)
	{
		print ("%s\n", e.what());
		return;
	}

	if (CurrentAddress.port == 0)
		CurrentAddress.port = 10666;

	Session.disconnect();
	Session.set_password (password);
	Session.connect (CurrentAddress);
}

// -------------------------------------------------------------------------------------------------
//
void Interface::set_player_names (const StringList& names)
{
	PlayerNames = names;
	NeedNicklistRender = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::tab_complete (const String& part, String complete)
{
	String& input = mutable_current_input();

	if (input.starts_with (part))
	{
		if (input[part.length()] != ' ')
			complete += ' ';

		input.replace (0, part.length(), complete);
		CursorPosition = complete.length();
		NeedInputRender = true;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::handle_command(const String& input)
{
	if (input[0] != '/')
		return;

	StringList args = input.right(input.length() - 1).split(" ");
	String command = args[0].to_lowercase();
	args.remove_at(0);

	if (command == "connect")
	{
		if (args.size() != 2)
		{
			print_error("Usage: /connect <address> <password>\n");
		}
		else
		{
			IPAddress address;

			try
			{
				address = IPAddress::from_string(args[0]);
			}
			catch (std::exception& e)
			{
				print_error("%s\n", e.what());
				return;
			}

			if (address.port == 0)
				address.port = 10666;

			Session.set_password(args[1]);
			Session.disconnect();
			Session.connect(CurrentAddress = address);
		}
	}
	else if (command == "disconnect")
	{
		Session.disconnect();
	}
	else if (command == "quit")
	{
		Session.disconnect();
		endwin();
		throw Exitception();
	}
	else
		print_error("Unknown command: %s\n", command.chars());
}

// -------------------------------------------------------------------------------------------------
//
void Interface::disconnected()
{
	print("Disconnected from %s\n", Session.address().to_string(IPAddress::WITH_PORT).chars());
	reset_title();
	render_full();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::reset_title()
{
	Title.sprintf (APPNAME " %s (%s)", full_version_string(), changeset_date_string());
}

// -------------------------------------------------------------------------------------------------
//
void Interface::flush_input()
{
	InputHistory.insert (0, "");
	InputCursor = 0;
	NeedInputRender = true;
}

END_ZFC_NAMESPACE

mercurial