sources/interface.cpp

Sun, 14 Dec 2014 23:38:26 +0200

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Sun, 14 Dec 2014 23:38:26 +0200
changeset 25
88b41eea08e0
parent 24
e651d02802c0
child 27
089e37c0887e
permissions
-rw-r--r--

- cleanup, refactor + better input handling

/*
	Copyright 2014 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 <string.h>
#include "interface.h"
#include "network/rconsession.h"
#include "network/ipaddress.h"

enum { PAGE_SIZE = 10 };

enum InputState
{
	INPUTSTATE_NORMAL,
	INPUTSTATE_ADDRESS,
	INPUTSTATE_PASSWORD,
	INPUTSTATE_CONFIRM_DISCONNECTION,
};

static String g_input;
static int g_cursor = 0;
static int g_pan = 0;
static bool g_needRefresh = false;
static bool g_needStatusBarRender = false;
static bool g_needInputRender = false;
static bool g_needOutputRender = false;
static String g_statusBarText;
static struct { char ch; int x; } g_cursorChar;
static Vector<String> g_output = {""};
static int g_outputScroll = 0;
static String g_title;
static InputState g_inputState = INPUTSTATE_NORMAL;
static IPAddress g_address;

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_color_pair (Color fg, Color bg) -> int
{
	return COLOR_PAIR ((int (fg) * NUM_COLORS) + int (bg));
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_prompt_string() -> String
{
	String prompt;

	switch (g_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;
}

// -------------------------------------------------------------------------------------------------
//
FUNCTION
Interface::initialize() -> void
{
	::initscr();
	::start_color();
	::raw();
	::keypad (stdscr, true);
	::noecho();
	::refresh();
	::timeout (0);
	g_title = format (APPNAME " %1 (%2)", full_version_string(), changeset_date_string());

	for (int i = 0; i < NUM_COLORS; ++i)
	for (int j = 0; j < NUM_COLORS; ++j)
	{
		init_pair ((i * NUM_COLORS + j),
			(i == DEFAULT) ? -1 : i,
			(j == DEFAULT) ? -1 : j);
	}

	render_full();
	refresh();
	g_needRefresh = false;
	print ("Interface initialized.\n");
}
// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_sessions_width() -> int
{
	return COLS / 3;
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_render_titlebar() -> void
{
	if (g_title.length() <= COLS)
	{
		int pair = interface_color_pair (WHITE, BLUE);
		int startx = (COLS - g_title.length()) / 2;
		int endx = startx + g_title.length();
		attron (pair);
		mvprintw (0, startx, "%s", g_title.chars());
		mvhline (0, 0, ' ', startx);
		mvhline (0, endx, ' ', COLS - endx);
		attroff (pair);
	}

	g_needRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
FUNCTION
Interface::set_title (const String& title) -> void
{
	g_title = title;
	interface_render_titlebar();
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_render_output() -> void
{
	int height = LINES - 3;

	// ensure we're within bounds
	if (g_outputScroll + height >= g_output.size())
		g_outputScroll = g_output.size() - height - 1;
	else if (g_outputScroll < 0)
		g_outputScroll = 0;

	int start = max (0, g_output.size() - height - 1 - g_outputScroll);
	int end = min (g_output.size(), start + height);
	int y = 1;
	assert (end - start <= height);

	for (int i = start; i < end; ++i)
	{
		mvhline (y, 0, ' ', COLS);
		mvprintw (y++, 0, "%s", g_output[i].chars());
	}

	g_needRefresh = true;
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_render_input() -> void
{
	int promptColor = interface_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 (g_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);
		return;
	}

	String prompt = interface_prompt_string();
	int displaylength = COLS - prompt.length() - 2;
	int y = LINES - 2;

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

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

	// What part of the string to draw?
	int start = g_pan;
	int end = min<int> (g_input.length(), start + displaylength);
	assert (g_cursor >= start and g_cursor <= end);

	// Render the input string
	mvhline (LINES - 2, 0, ' ', COLS);
	mvprintw (y, prompt.length() + 1, "%s", g_input.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).
	g_cursorChar.ch = g_cursor != 0 ? g_input[g_cursor - 1] : '\0';
	g_cursorChar.x = prompt.length() + (g_cursor - g_pan);
	g_needRefresh = true;
	g_needInputRender = false;
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_render_statusbar() -> void
{
	int y = LINES - 1;
	mvhline (y, 0, ' ', COLS);
	mvprintw (y, 0, "%s", g_statusBarText.chars());
	g_needRefresh = true;
	g_needStatusBarRender = false;
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
set_statusbar_text (const String& a) -> void
{
	g_statusBarText = a;
	g_needStatusBarRender = true;
}

// -------------------------------------------------------------------------------------------------
//
FUNCTION
Interface::render_full() -> void
{
	interface_render_titlebar();
	interface_render_output();
	interface_render_statusbar();
	interface_render_input();
}

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
interface_position_cursor() -> void
{
	// This is only relevant if the input string is being drawn
	if (g_inputState == INPUTSTATE_CONFIRM_DISCONNECTION)
		return;

	int y = LINES - 2;

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

// -------------------------------------------------------------------------------------------------
//
static FUNCTION
set_input_state (InputState newstate) -> void
{
	// Clear the input row (unless going to or from confirm state)
	if (newstate != INPUTSTATE_CONFIRM_DISCONNECTION
		and g_inputState != INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		g_input.clear();
	}

	switch (newstate)
	{
	case INPUTSTATE_ADDRESS:
		if (g_address.host != 0)
			g_input = g_address.to_string (IP_WITH_PORT);
		break;

	default:
		break;
	}

	g_inputState = newstate;
	g_needInputRender = true;
}

// -------------------------------------------------------------------------------------------------
//
FUNCTION
Interface::handle_input() -> void
{
	int ch = ::getch();
	set_statusbar_text (String::from_number (ch));

	if (g_inputState == INPUTSTATE_CONFIRM_DISCONNECTION)
	{
		if (ch == 'y' or ch == 'Y')
			set_input_state (INPUTSTATE_ADDRESS);
		else if (ch == 'n' or ch == 'N')
			set_input_state (INPUTSTATE_NORMAL);
		return;
	}

	if (ch >= 0x20 and ch <= 0x7E)
	{
		g_input.insert (g_cursor++, char (ch));
		g_needInputRender = true;
	}
	else switch (ch)
	{
	case KEY_F(1):
		endwin();
		exit (EXIT_SUCCESS);
		break;

	case KEY_LEFT:
		if (g_cursor > 0)
		{
			g_cursor--;
			g_needInputRender = true;
		}
		break;

	case KEY_RIGHT:
		if (g_cursor < g_input.length())
		{
			g_cursor++;
			g_needInputRender = true;
		}
		break;

	case KEY_HOME:
		if (g_cursor != 0)
		{
			g_cursor = 0;
			g_needInputRender = true;
		}
		break;

	case KEY_END:
		if (g_cursor != g_input.length())
		{
			g_cursor = g_input.length();
			g_needInputRender = true;
		}
		break;

	case KEY_BACKSPACE:
		if (g_cursor > 0)
		{
			g_input.remove_at (--g_cursor);
			g_needInputRender = true;
		}
		break;

	case KEY_DC:
		if (g_cursor < g_input.length())
		{
			g_input.remove_at (g_cursor);
			g_needInputRender = true;
		}
		break;

	case KEY_PPAGE:
		g_outputScroll += PAGE_SIZE;
		g_needOutputRender = true;
		break;

	case KEY_NPAGE:
		g_outputScroll -= PAGE_SIZE;
		g_needOutputRender = true;
		break;

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

		case INPUTSTATE_ADDRESS:
			try
			{
				g_address = IPAddress::from_string (g_input);
			}
			catch (std::exception& e)
			{
				print (e.what());
				return;
			}

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

			set_input_state (INPUTSTATE_PASSWORD);
			break;

		case INPUTSTATE_PASSWORD:
			if (g_inputState == INPUTSTATE_PASSWORD and not g_input.is_empty())
			{
				RCONSession* session = RCONSession::new_session();
				session->set_password (g_input);
				session->connect (g_address);
				set_input_state (INPUTSTATE_NORMAL);
			}
			break;

		case INPUTSTATE_NORMAL:
			if (RCONSession::get_session() != nullptr
				and RCONSession::get_session()->send_command (g_input))
			{
				g_input.clear();
				g_needInputRender = true;
			}
			break;
		}
		break;

	case 'N' - 'A' + 1: // ^N
		if (g_inputState == INPUTSTATE_NORMAL)
		{
			if (RCONSession::get_session() != nullptr
				and RCONSession::get_session()->state() != RCON_DISCONNECTED)
			{
				set_input_state (INPUTSTATE_CONFIRM_DISCONNECTION);
			}
			else
			{
				set_input_state (INPUTSTATE_ADDRESS);
			}
		}
		break;
	}
}

// -------------------------------------------------------------------------------------------------
//
FUNCTION
Interface::render() -> void
{
	if (g_needStatusBarRender) interface_render_statusbar();
	if (g_needInputRender) interface_render_input();
	if (g_needOutputRender) interface_render_output();

	if (g_needRefresh)
	{
		interface_position_cursor();
		refresh();
		g_needRefresh = false;
	}
}

// -------------------------------------------------------------------------------------------------
//
FUNCTION print_to_console (const String& a) -> void
{
	for (char ch : a)
	{
		if (ch == '\n')
		{
			g_output << "";
			continue;
		}

		g_output[g_output.size() - 1] += ch;
	}

	g_needOutputRender = true;
}

mercurial