sources/interface.cpp

Thu, 28 Jan 2021 11:39:48 +0200

author
Teemu Piippo <teemu@hecknology.net>
date
Thu, 28 Jan 2021 11:39:48 +0200
branch
protocol5
changeset 199
927f4b8ef6f7
parent 195
be953e1621d9
permissions
-rw-r--r--

merged with default

/*
	Copyright 2014 - 2021 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 PAGE_SIZE = 10;

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

// -------------------------------------------------------------------------------------------------
//
const std::string& Interface::getCurrentInput()
{
	return this->m_inputHistory[this->m_inputCursor];
}

// -------------------------------------------------------------------------------------------------
//
// Makes current_input() the lastmost input(so that we won't modify history)
//
void Interface::detachInput()
{
	if (this->m_inputCursor > 0)
	{
		this->m_inputHistory[0] = getCurrentInput();
		this->m_inputCursor = 0;
	}
}

// -------------------------------------------------------------------------------------------------
// A version of current_input() that allows changing the contents of it.
//
std::string& Interface::getEditableInput()
{
	detachInput();
	return this->m_inputHistory[this->m_inputCursor];
}

// -------------------------------------------------------------------------------------------------
//
void Interface::moveInputCursor(int delta)
{
	// No input history when inputting addresses or passwords
	if (this->m_inputState != INPUTSTATE_NORMAL)
	{
		this->m_inputCursor = 0;
		return;
	}

	int oldcursor = this->m_inputCursor;
	this->m_inputCursor = clamp(this->m_inputCursor + delta, 0, static_cast<int>(this->m_inputHistory.size() - 1));

	if (this->m_inputCursor != oldcursor)
	{
		this->m_cursorPosition = getCurrentInput().length();
		this->m_needInputRender = true;
	}
}

// -------------------------------------------------------------------------------------------------
//
std::string Interface::getPromptString()
{
	std::string prompt;

	switch (this->m_inputState)
	{
	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::setInputState(InputState newstate)
{
	// Clear the input row(unless going to or from confirm state)
	if (newstate != INPUTSTATE_CONFIRM_DISCONNECTION
		and this->m_inputState != INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		this->m_inputCursor = 0;
		getEditableInput().clear();
	}

	switch (newstate)
	{
	case INPUTSTATE_ADDRESS:
		if (this->m_remoteAddress.host != 0)
			getEditableInput() = net::ip_address_to_string(this->m_remoteAddress);
		break;

	default:
		break;
	}

	this->m_inputState = newstate;
	this->m_needInputRender = true;
}

// -------------------------------------------------------------------------------------------------
//
Interface::Interface() :
	m_inputCursor(0),
	m_cursorPosition(0),
	m_inputPanning(0),
	m_needRefresh(false),
	m_needStatusBarRender(false),
	m_needInputRender(false),
	m_needOutputRender(false),
	m_needNicklistRender(false),
	m_outputScroll(0),
	m_inputState(INPUTSTATE_NORMAL),
	m_disconnectCallback(nullptr)
{
	::initscr();
	::raw();
	::keypad(stdscr, true);
	::noecho();
	::refresh();
	::timeout(0);
	this->m_inputHistory.clear();
	this->m_inputHistory.push_back("");
	this->m_outputLines.clear();
	this->m_outputLines.push_back(ColoredLine());
	this->m_session.setInterface(this);
	resetTitle();

	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 += 1)
		for (int j = 0; j < NUM_COLORS; j += 1)
		{
			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)
					printWarning("Unable to initialize color pair %d(%d, %d)\n", pairnum, fg, bg);
			}
		}
	}

	renderFull();
	refresh();
	this->m_needRefresh = false;
}

Interface::~Interface()
{
	::endwin();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::renderTitlebar()
{
	if (static_cast<signed>(this->m_title.length()) <= COLS)
	{
		chtype pair = getColorPair(WHITE, BLUE);
		int startx =(COLS - this->m_title.length()) / 2;
		int endx = startx + this->m_title.length();
		attron(pair);
		mvprintw(0, startx, "%s", this->m_title.data());
		mvhline(0, 0, ' ', startx);
		mvhline(0, endx, ' ', COLS - endx);
		attroff(pair);
	}

	this->m_needRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::setTitle(const std::string& title)
{
	this->m_title = title;
	renderTitlebar();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::safeDisconnect(std::function<void(bool)> afterwards)
{
	if (this->m_session.isActive())
	{
		this->m_disconnectCallback = afterwards;
		setInputState(INPUTSTATE_CONFIRM_DISCONNECTION);
	}
	else
		afterwards(false);
}

// -------------------------------------------------------------------------------------------------
//
int Interface::nicklistWidth()
{
	// 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::renderColorline(int y, int x0, int width, const ColoredLine& line, bool allowWrap)
{
	int x = x0;

	for (int byte : line.data())
	{
		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)(getColorPair(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::renderOutput()
{
	if (this->m_outputLines.size() == 1)
		return;

	this->m_outputScroll = clamp(this->m_outputScroll, 0, static_cast<signed>(this->m_outputLines.size() - 1));

	int height = LINES - 3;
	int width = COLS - nicklistWidth();
	int printOffset = 0;
	int end = this->m_outputLines.size() - 1 - this->m_outputScroll;
	int start = end;
	int usedHeight = 0;
	int y = 1;
	bool tightFit = false;

	// Where to start?
	while (start > 0)
	{
		int rows = this->m_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 < static_cast<int>(this->m_outputLines.size()))
		{
			int rows = this->m_outputLines[end].rows(width);

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

			end++;
			usedHeight += rows;
		}
	}

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

	this->m_outputScroll = this->m_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 = 0; i < height; i += 1)
		mvhline(y + i, 0, ' ', width);

	// Print the lines
	y += printOffset;

	for (int i = start; i < end; i += 1)
		y = renderColorline(y, 0, width, this->m_outputLines[i], true);

	this->m_needOutputRender = false;
	this->m_needRefresh = true;
}

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

	if (width > 0)
		return;

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

		if (i < static_cast<signed>(this->m_playerNames.size()))
			renderColorline(y, x, width, this->m_playerNames[i], false);

		y++;
	}

	this->m_needNicklistRender = false;
	this->m_needRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::renderInput()
{
	chtype promptColor = getColorPair(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 (this->m_inputState == 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);
		this->m_needRefresh = true;
		return;
	}

	std::string prompt = getPromptString();
	int displayLength = COLS - prompt.length() - 2;
	std::string displayString = getCurrentInput();
	int y = LINES - 2;

	// If we're inputting a password, replace it with asterisks
	if (this->m_inputState == INPUTSTATE_PASSWORD)
	{
		for (char &ch : displayString)
			ch = '*';
	}

	// Ensure the cursor is within bounds
	this->m_cursorPosition = clamp(this->m_cursorPosition, 0, static_cast<signed>(displayString.length()));

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

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

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

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

	// Store in memory where the cursor is now(so that we can re-draw it to position the terminal
	// cursor).
	this->m_cursorCharacter.ch = this->m_cursorPosition != 0 ? displayString[this->m_cursorPosition - 1] : '\0';
	this->m_cursorCharacter.x = prompt.length() + (this->m_cursorPosition - this->m_inputPanning);
	this->m_needRefresh = true;
	this->m_needInputRender = false;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::renderStatusBar()
{
	chtype color = getColorPair(WHITE, BLUE);
	int y = LINES - 1;
	attron(color);
	mvhline(y, 0, ' ', COLS);
	mvprintw(y, 0, "%s", this->m_statusBarText.data());
	attroff(color);
	this->m_needRefresh = true;
	this->m_needStatusBarRender = false;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::updateStatusBar()
{
	std::string text;

	switch (this->m_session.getState())
	{
	case RCON_DISCONNECTED:
		text = "Disconnected.";
		break;

	case RCON_CONNECTING:
	case RCON_AUTHENTICATING:
		text = "Connecting to " + net::ip_address_to_string(this->m_session.address()) + "...";
		break;

	case RCON_CONNECTED:
		{
			std::string adminText;

			if (this->m_session.getAdminCount() == 0)
			{
				adminText = "No other admins";
			}
			else
			{
				adminText = zfc::sprintf("%d other admin%s", this->m_session.getAdminCount(),
					this->m_session.getAdminCount() != 1 ? "s" : "");
			}

			text = zfc::sprintf("%s | %s | %s",
				net::ip_address_to_string(this->m_session.address()).data(),
				this->m_session.getLevel().data(),
				adminText.data());
		}
		break;
	}

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

	text += "Ctrl+N to connect, Ctrl+Q to ";
	text +=(this->m_session.getState() == RCON_DISCONNECTED) ? "quit" : "disconnect";

	if (text != this->m_statusBarText)
	{
		this->m_statusBarText = text;
		this->m_needStatusBarRender = true;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::renderFull()
{
	updateStatusBar();
	renderTitlebar();
	renderOutput();
	renderStatusBar();
	renderInput();
	renderNicklist();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::positionCursor()
{
	// This is only relevant if the input string is being drawn
	if (this->m_inputState == INPUTSTATE_CONFIRM_DISCONNECTION)
		return;

	int y = LINES - 2;

	if (this->m_cursorCharacter.ch != '\0')
		mvprintw(y, this->m_cursorCharacter.x, "%c", this->m_cursorCharacter.ch);
	else
		mvprintw(y, getPromptString().length(), " ");
}

// -------------------------------------------------------------------------------------------------
//
int Interface::findPreviousWord()
{
	const std::string& input = getCurrentInput();
	int pos = this->m_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::findNextWord()
{
	const std::string& input = getCurrentInput();
	int pos = this->m_cursorPosition;

	// Move past current whitespace
	while (pos < static_cast<signed>(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 (this->m_cursorPosition > a and this->m_cursorPosition <= b)
		this->m_cursorPosition = a;

	std::string& input = getEditableInput();
	this->m_pasteBuffer = mid(input, a, b);
	input = remove_range(input, a, b - a);
	this->m_needInputRender = true;
}

bool Interface::tryResolveAddress(const std::string &address_string, net::ip_address* target)
{
	std::stringstream errors;
	const std::optional<net::ip_address> address_opt = net::ip_resolve(address_string, errors);
	if (address_opt.has_value())
	{
		*target = address_opt.value();
		if (target->port == 0)
		{
			target->port = 10666;
		}
		return true;
	}
	else
	{
		this->printError("%s\n", errors.str().data());
		return false;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::handleInput(bool* shouldquit)
{
	int ch = ::getch();

	if (ch < 0)
		return;

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

	if (this->m_inputState == INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		if (ch == 'y' or ch == 'Y')
		{
			this->m_session.disconnect();
			this->m_disconnectCallback(true);
			this->updateStatusBar();
		}
		else if (ch == 'n' or ch == 'N')
			setInputState(INPUTSTATE_NORMAL);

		return;
	}

	if (ch >= 0x20 and ch <= 0x7E)
	{
		std::string& input = getEditableInput();
		input.insert(input.begin() + this->m_cursorPosition, char(ch));
		this->m_cursorPosition += 1;
		this->m_needInputRender = true;
	}
	else switch (ch)
	{
	case 'Q' - 'A' + 1: // ^Q
		switch (this->m_inputState)
		{
		case INPUTSTATE_CONFIRM_DISCONNECTION:
			break;

		case INPUTSTATE_NORMAL:
			safeDisconnect([&](bool hadsession)
			{
				if (hadsession)
				{
					setInputState(INPUTSTATE_NORMAL);
				}
				else
				{
					*shouldquit = true;
				}
			});
			break;

		case INPUTSTATE_PASSWORD:
			setInputState(INPUTSTATE_ADDRESS);
			break;

		case INPUTSTATE_ADDRESS:
			setInputState(INPUTSTATE_NORMAL);
		}
		break;

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

	case KEY_RIGHT:
	case 'F' - 'A' + 1: // readline ^F
		if (this->m_cursorPosition < static_cast<int>(getCurrentInput().length()))
		{
			this->m_cursorPosition++;
			this->m_needInputRender = true;
		}
		break;

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

	case KEY_HOME:
	case 'A' - 'A' + 1: // readline ^A
		if (this->m_cursorPosition != 0)
		{
			this->m_cursorPosition = 0;
			this->m_needInputRender = true;
		}
		break;

	case KEY_END:
	case 'E' - 'A' + 1: // readline ^E
		if (this->m_cursorPosition != static_cast<signed>(getCurrentInput().length()))
		{
			this->m_cursorPosition = getCurrentInput().length();
			this->m_needInputRender = true;
		}
		break;

	case KEY_BACKSPACE:
	case '\b':
		if (this->m_cursorPosition > 0)
		{
			std::string& input = getEditableInput();
			input.erase(input.begin() + this->m_cursorPosition - 1);
			this->m_cursorPosition -= 1;
			this->m_needInputRender = true;
		}
		break;

	case KEY_DC:
	case 'D' - 'A' + 1: // readline ^D
		if (this->m_cursorPosition < static_cast<signed>(getCurrentInput().length()))
		{
			std::string& input = getEditableInput();
			input.erase(input.begin() + this->m_cursorPosition);
			this->m_needInputRender = true;
		}
		break;

	case KEY_PPAGE:
		this->m_outputScroll += min(PAGE_SIZE, LINES / 2);
		this->m_needOutputRender = true;
		break;

	case KEY_NPAGE:
		this->m_outputScroll -= min(PAGE_SIZE, LINES / 2);
		this->m_needOutputRender = true;
		break;

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

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

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

	case 'Y' - 'A' + 1: // readline ^Y - paste previously deleted text
		if (not this->m_pasteBuffer.empty())
		{
			getEditableInput().insert(this->m_cursorPosition, this->m_pasteBuffer);
			this->m_cursorPosition += this->m_pasteBuffer.length();
			this->m_needInputRender = true;
		}
		break;

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

			if (this->m_inputState == INPUTSTATE_NORMAL
				and this->m_cursorPosition > 0
				and(space == -1 or space >= this->m_cursorPosition))
			{
				std::string start = mid(getCurrentInput(), 0, this->m_cursorPosition);
				this->m_session.requestTabCompletion(start);
			}
		}
		break;

	case '\n':
	case '\r':
	case KEY_ENTER:
		switch (this->m_inputState)
		{
		case INPUTSTATE_CONFIRM_DISCONNECTION:
			break; // handled above

		case INPUTSTATE_ADDRESS:
			if (this->tryResolveAddress(this->getCurrentInput(), &this->m_remoteAddress))
			{
				setInputState(INPUTSTATE_PASSWORD);
			}
			break;

		case INPUTSTATE_PASSWORD:
			if (this->m_inputState == INPUTSTATE_PASSWORD and not getCurrentInput().empty())
			{
				this->m_session.disconnect();
				this->m_session.setPassword(getCurrentInput());
				this->m_session.connect(this->m_remoteAddress);
				setInputState(INPUTSTATE_NORMAL);
			}
			break;

		case INPUTSTATE_NORMAL:
			if (getCurrentInput()[0] == '/')
			{
				handleCommand(getCurrentInput(), shouldquit);
				flushInput();
			}
			else if (this->m_session.sendCommand(getCurrentInput()))
			{
				flushInput();
			}
			break;
		}
		break;

	case 'N' - 'A' + 1: // ^N
		if (this->m_inputState == INPUTSTATE_NORMAL)
			safeDisconnect([&](bool){setInputState(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
				this->m_cursorPosition = findPreviousWord();
				this->m_needInputRender = true;
				break;

			case 'f':
			case 'F':
				// readline alt-f - move one word to the right
				this->m_cursorPosition = findNextWord();
				this->m_needInputRender = true;
				break;

			case 'd':
			case 'D':
				// readline alt-d - delete from here till next word boundary
				yank(this->m_cursorPosition, findNextWord());
				break;

			case KEY_BACKSPACE: // alt+backspace, remove previous word
			case '\b':
				yank(findPreviousWord(), this->m_cursorPosition);
				break;
			}
		}
		else
		{
			// No alt-key, handle pure escape
			if (this->m_inputState == INPUTSTATE_PASSWORD)
				setInputState(INPUTSTATE_ADDRESS);
			else if (this->m_inputState == INPUTSTATE_ADDRESS)
				setInputState(INPUTSTATE_NORMAL);
		}
		break;
	}

	render();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::render()
{
	if (this->m_needStatusBarRender) renderStatusBar();
	if (this->m_needInputRender) renderInput();
	if (this->m_needOutputRender) renderOutput();
	if (this->m_needNicklistRender) renderNicklist();

	if (this->m_needRefresh)
	{
		positionCursor();
		refresh();
		this->m_needRefresh = false;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::vprint(const char* fmtstr, va_list args)
{
	std::string message;
	message = vsprintf(fmtstr, args);
	printToConsole(message);
}

// -------------------------------------------------------------------------------------------------
//
void __cdecl Interface::printText(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);
	printToConsole(TEXTCOLOR_BrightBlue);
	vprint(fmtstr, args);
	va_end(args);
}

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

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

// -------------------------------------------------------------------------------------------------
//
void Interface::printToConsole(std::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.
	replace_all(message, "\\c", "\x1C");

	for (char ch : message)
	{
		if (ch == '\n')
		{
			zfc::last(this->m_outputLines).finalize();
			this->m_outputLines.push_back({});
			continue;
		}

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

			for (char ch : std::string(timestamp))
				zfc::last(this->m_outputLines).addChar(ch);
		}

		// Remove some lines if there's too many of them. 20,000 should be enough, I hope.
		while (this->m_outputLines.size() > 20000)
			this->m_outputLines.erase(this->m_outputLines.begin());

		zfc::last(this->m_outputLines).addChar(ch);
	}

	this->m_needOutputRender = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::connect(std::string address_string, std::string password)
{
	if (this->tryResolveAddress(address_string, &this->m_remoteAddress))
	{
		this->m_session.disconnect();
		this->m_session.setPassword(password);
		this->m_session.connect(this->m_remoteAddress);
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::setPlayerNames(const std::vector<std::string>& names)
{
	this->m_playerNames.clear();

	for (const std::string& name : names)
	{
		ColoredLine coloredname;
		coloredname.addString(name);
		coloredname.finalize();
		this->m_playerNames.push_back(coloredname);
	}

	this->m_needNicklistRender = true;
}

// -------------------------------------------------------------------------------------------------
//
void Interface::tabComplete(const std::string& part, std::string complete)
{
	std::string& input = getEditableInput();

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

		input.replace(0, part.length(), complete);
		this->m_cursorPosition = complete.length();
		this->m_needInputRender = true;
	}
}

// -------------------------------------------------------------------------------------------------
//
void Interface::handleCommand(const std::string& input, bool* shouldquit)
{
	if (input[0] != '/')
		return;

	std::vector<std::string> args = split(right(input, input.length() - 1), " ");
	std::string command = to_lowercase(args[0]);
	args.erase(args.begin());

	if (command == "connect")
	{
		if (args.size() != 2)
		{
			printError("Usage: /connect <address> <password>\n");
		}
		else
		{
			this->connect(args[0], args[1]);
		}
	}
	else if (command == "disconnect")
	{
		this->m_session.disconnect();
	}
	else if (command == "quit")
	{
		this->m_session.disconnect();
		*shouldquit = true;
	}
	else if (command == "watch")
	{
		if (not args.empty())
			m_session.requestWatch(args);
		else
			printError("No CVars to watch.\n");
	}
	else
		printError("Unknown command: %s\n", command.data());
}

// -------------------------------------------------------------------------------------------------
//
void Interface::disconnected()
{
	print("Disconnected from %s\n", net::ip_address_to_string(this->m_session.address()).data());
	resetTitle();
	renderFull();
}

// -------------------------------------------------------------------------------------------------
//
void Interface::resetTitle()
{
	this->m_title = sprintf("%s %s (%s)", application_name(), full_version_string(), changeset_date_string());
}

// -------------------------------------------------------------------------------------------------
//
void Interface::flushInput()
{
	this->m_inputHistory.insert(this->m_inputHistory.begin(), "");
	this->m_inputCursor = 0;
	this->m_needInputRender = true;
}

END_ZFC_NAMESPACE

mercurial