Mon, 15 Dec 2014 10:31:52 +0200
- added experimental support for rcon tab-completion
/* 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 { RLINE_ON_BLACK = 256, RLINE_ON_RED, RLINE_ON_GREEN, RLINE_ON_YELLOW, RLINE_ON_BLUE, RLINE_ON_MAGENTA, RLINE_ON_CYAN, RLINE_ON_WHITE, RLINE_ON_BOLD, RLINE_OFF_BLACK, RLINE_OFF_RED, RLINE_OFF_GREEN, RLINE_OFF_YELLOW, RLINE_OFF_BLUE, RLINE_OFF_MAGENTA, RLINE_OFF_CYAN, RLINE_OFF_WHITE, RLINE_OFF_BOLD, }; class RendererLine { public: RendererLine() {} METHOD data() const -> const Vector<int>& { return m_data; } METHOD length() const -> int { return m_length; } METHOD add_char (char ch) -> void; METHOD finalize() -> void; METHOD rows (int cols) const -> int; private: METHOD set_color (Color a, bool on) -> void; Vector<int> m_data; int m_length = 0; bool m_final = false; Color m_activeColor = DEFAULT; bool m_boldActive = false; int m_colorCodeStage = 0; String m_string; }; static const int g_pageSize = 10; enum InputState { INPUTSTATE_NORMAL, INPUTSTATE_ADDRESS, INPUTSTATE_PASSWORD, INPUTSTATE_CONFIRM_DISCONNECTION, }; static StringList g_input; static int g_inputCursor = 0; 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 struct { char ch; int x; } g_cursorChar; static Vector<RendererLine> g_output;; static int g_outputScroll = 0; static String g_title; static InputState g_inputState = INPUTSTATE_NORMAL; static Function<void (void)> g_disconnectConfirmFunction = nullptr; static IPAddress g_address; static String g_statusBarText; static const struct { Color color; bool bold; } g_colorCodes['v' - 'a' + 1] = { { RED, true }, // a - brick { YELLOW, true }, // b - tan { WHITE, false }, // c - gray { GREEN, true }, // d - light green { YELLOW, false }, // e - brown { YELLOW, true }, // f - gold yellow { RED, true }, // g - bright red { BLUE, false }, // h - dark blue { YELLOW, false }, // i - orange { WHITE, true }, // j - white { YELLOW, true }, // k - fire yellow { DEFAULT, false }, // l - untranslated { BLACK, false }, // m - black { BLUE, true }, // n - light blue { YELLOW, true }, // o - cream { GREEN, true }, // p - olive green { GREEN, false }, // q - dark green { RED, false }, // r - dark red { YELLOW, false }, // s - dark brown { MAGENTA, false }, // t - purple { BLACK, true }, // u - dark gray { CYAN, true }, // v - cyan }; // ------------------------------------------------------------------------------------------------- // static FUNCTION interface_color_pair (Color fg, Color bg) -> int { return COLOR_PAIR ((int (fg) * NUM_COLORS) + int (bg)); } // ------------------------------------------------------------------------------------------------- // static FUNCTION current_input() -> const String& { return g_input[g_inputCursor]; } // ------------------------------------------------------------------------------------------------- // // Makes current_input() the lastmost input (so that we won't modify history) // static FUNCTION detach_input() -> void { if (g_inputCursor > 0) { g_input[0] = current_input(); g_inputCursor = 0; } } // ------------------------------------------------------------------------------------------------- // A version of current_input() that allows changing the contents of it. // static FUNCTION mutable_current_input() -> String& { detach_input(); return g_input[g_inputCursor]; } // ------------------------------------------------------------------------------------------------- // static FUNCTION move_input_cursor (int delta) -> void { // No input history when inputting addresses or passwords if (g_inputState != INPUTSTATE_NORMAL) { g_inputCursor = 0; return; } int oldcursor = g_inputCursor; g_inputCursor = clamp (g_inputCursor + delta, 0, g_input.size() - 1); if (g_inputCursor != oldcursor) { g_cursor = current_input().length(); g_needInputRender = true; } } // ------------------------------------------------------------------------------------------------- // 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; } // ------------------------------------------------------------------------------------------------- // 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_inputCursor = 0; mutable_current_input().clear(); } switch (newstate) { case INPUTSTATE_ADDRESS: if (g_address.host != 0) mutable_current_input() = g_address.to_string (IP_WITH_PORT); break; default: break; } g_inputState = newstate; g_needInputRender = true; } // ------------------------------------------------------------------------------------------------- // FUNCTION Interface::initialize() -> void { ::initscr(); ::start_color(); ::raw(); ::keypad (stdscr, true); ::noecho(); ::refresh(); ::timeout (0); ::use_default_colors(); g_input.clear(); g_input << ""; g_output.clear(); g_output << RendererLine(); 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; } // ------------------------------------------------------------------------------------------------- // 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 safe_disconnect (Function<void()> afterwards) -> void { if (RCONSession::get_session()->is_active()) { g_disconnectConfirmFunction = afterwards; set_input_state (INPUTSTATE_CONFIRM_DISCONNECTION); } else afterwards(); } // ------------------------------------------------------------------------------------------------- // static FUNCTION interface_render_output() -> void { if (g_output.size() == 1) return; g_outputScroll = clamp (g_outputScroll, 0, g_output.size() - 1); int height = LINES - 3; int printOffset = 0; int end = g_output.size() - 1 - g_outputScroll; int start = end; int usedHeight = 0; int y = 1; bool tightFit = false; // Where to start? while (start > 0) { int rows = g_output[start - 1].rows (COLS); 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 < g_output.size()) { int rows = g_output[end].rows (COLS); if (usedHeight + rows > height) { tightFit = true; break; } end++; usedHeight += rows; } } if (start > 0) printOffset = height - usedHeight; g_outputScroll = g_output.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, ' ', COLS); // Print the lines y += printOffset; for (int i = start; i < end; ++i) { int x = 0; for (int byte : g_output[i].data()) { if (x == COLS) { x = 0; ++y; } if (isprint (byte)) mvaddch (y, x++, char (byte)); else switch (byte) { case RLINE_ON_BLACK: case RLINE_ON_GREEN: case RLINE_ON_YELLOW: case RLINE_ON_BLUE: case RLINE_ON_MAGENTA: case RLINE_ON_CYAN: case RLINE_ON_WHITE: attron (interface_color_pair (Color (byte - RLINE_ON_BLACK), DEFAULT)); break; case RLINE_OFF_BLACK: case RLINE_OFF_GREEN: case RLINE_OFF_YELLOW: case RLINE_OFF_BLUE: case RLINE_OFF_MAGENTA: case RLINE_OFF_CYAN: case RLINE_OFF_WHITE: attroff (interface_color_pair (Color (byte - RLINE_OFF_BLACK), DEFAULT)); break; case RLINE_ON_BOLD: attron (A_BOLD); break; case RLINE_OFF_BOLD: attroff (A_BOLD); break; } } ++y; } g_needOutputRender = false; 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; String displayString = current_input(); int y = LINES - 2; // If we're inputting a password, replace it with asterisks if (g_inputState == INPUTSTATE_PASSWORD) { for (char& ch : displayString) ch = '*'; } // Ensure the cursor is within bounds g_cursor = clamp (g_cursor, 0, displayString.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> (displayString.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", displayString.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 ? displayString[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 color = interface_color_pair (WHITE, BLUE); int y = LINES - 1; attron (color); mvhline (y, 0, ' ', COLS); mvprintw (y, 0, "%s", g_statusBarText.chars()); attroff (color); g_needRefresh = true; g_needStatusBarRender = false; } // ------------------------------------------------------------------------------------------------- // FUNCTION Interface::update_statusbar() -> void { String text; RCONSession* session = RCONSession::get_session(); switch (session->state()) { case RCON_DISCONNECTED: text = "Disconnected."; break; case RCON_CONNECTING: case RCON_AUTHENTICATING: text = "Connecting to " + session->address().to_string (IP_WITH_PORT) + "..."; break; case RCON_CONNECTED: { String adminText = (session->num_admins() == 0) ? "No other admins" : format ("%1 other admin%s1", session->num_admins()); text = format ("%1 | %2 | %3", session->address().to_string (IP_WITH_PORT), session->level(), adminText); } break; } if (not text.is_empty()) text += " | "; text += "^N to connect, ^Q to quit"; if (text != g_statusBarText) { g_statusBarText = text; g_needStatusBarRender = true; } } // ------------------------------------------------------------------------------------------------- // FUNCTION Interface::render_full() -> void { update_statusbar(); 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(), " "); } // ------------------------------------------------------------------------------------------------- // FUNCTION Interface::handle_input() -> void { int ch = ::getch(); if (ch == KEY_RESIZE) { ::clear(); render_full(); return; } if (g_inputState == INPUTSTATE_CONFIRM_DISCONNECTION) { if (ch == 'y' or ch == 'Y') { RCONSession::get_session()->disconnect(); g_disconnectConfirmFunction(); } else if (ch == 'n' or ch == 'N') set_input_state (INPUTSTATE_NORMAL); return; } if (ch >= 0x20 and ch <= 0x7E) { mutable_current_input().insert (g_cursor++, char (ch)); g_needInputRender = true; } else switch (ch) { case 'Q' - 'A' + 1: // ^Q switch (g_inputState) { case INPUTSTATE_CONFIRM_DISCONNECTION: break; case INPUTSTATE_NORMAL: safe_disconnect ([]() { RCONSession* session = RCONSession::get_session(); if (session->is_active()) { session->disconnect(); 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 '\e': if (g_inputState == INPUTSTATE_PASSWORD) set_input_state (INPUTSTATE_ADDRESS); else if (g_inputState == INPUTSTATE_ADDRESS) set_input_state (INPUTSTATE_NORMAL); break; case KEY_LEFT: if (g_cursor > 0) { g_cursor--; g_needInputRender = true; } break; case KEY_RIGHT: if (g_cursor < current_input().length()) { g_cursor++; g_needInputRender = true; } break; case KEY_DOWN: case KEY_UP: move_input_cursor (ch == KEY_DOWN ? -1 : 1); break; case KEY_HOME: if (g_cursor != 0) { g_cursor = 0; g_needInputRender = true; } break; case KEY_END: if (g_cursor != current_input().length()) { g_cursor = current_input().length(); g_needInputRender = true; } break; case KEY_BACKSPACE: if (g_cursor > 0) { mutable_current_input().remove_at (--g_cursor); g_needInputRender = true; } break; case KEY_DC: if (g_cursor < current_input().length()) { mutable_current_input().remove_at (g_cursor); g_needInputRender = true; } break; case KEY_PPAGE: g_outputScroll += min (g_pageSize, LINES / 2); g_needOutputRender = true; break; case KEY_NPAGE: g_outputScroll -= min (g_pageSize, LINES / 2); g_needOutputRender = true; break; case '\t': { int space = current_input().find (" "); if (g_inputState == INPUTSTATE_NORMAL and g_cursor > 0 and (space == -1 or space >= g_cursor)) { RCONSession::get_session()->request_tab_complete (current_input().mid (0, g_cursor)); } } 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 (current_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 current_input().is_empty()) { RCONSession* session = RCONSession::new_session(); session->set_password (current_input()); session->connect (g_address); set_input_state (INPUTSTATE_NORMAL); } break; case INPUTSTATE_NORMAL: if (RCONSession::get_session()->send_command (current_input())) { g_input.insert (0, ""); g_needInputRender = true; } break; } break; case 'N' - 'A' + 1: // ^N if (g_inputState == INPUTSTATE_NORMAL) safe_disconnect ([]() {set_input_state (INPUTSTATE_ADDRESS);}); break; } render(); } // ------------------------------------------------------------------------------------------------- // 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 (String a) -> void { // Zandronum is retarded and SOMETIMES sends color codes as "\\c" and sometimes as "\x1C". // Let's correct that on our end and HOPE this won't cause conflicts. a.replace ("\\c", "\x1C"); for (char ch : a) { if (ch == '\n') { g_output[g_output.size() - 1].finalize(); g_output << RendererLine(); continue; } g_output[g_output.size() - 1].add_char (ch); } g_needOutputRender = true; } // ------------------------------------------------------------------------------------------------- // FUNCTION Interface::connect (String address, String password) -> void { try { g_address = IPAddress::from_string (address); } catch (std::exception& e) { print (e.what()); return; } if (g_address.port == 0) g_address.port = 10666; RCONSession* session = RCONSession::new_session(); session->set_password (password); session->connect (g_address); } // ------------------------------------------------------------------------------------------------- // METHOD RendererLine::finalize() -> void { if (m_activeColor != DEFAULT) this->set_color (m_activeColor, false); if (m_boldActive) m_data << RLINE_OFF_BOLD; m_final = true; } // ------------------------------------------------------------------------------------------------- // METHOD RendererLine::add_char (char ch) -> void { if (m_final) return; // Don't touch finalized lines. if (ch == '\x1C' and m_colorCodeStage == 0) { m_colorCodeStage = 1; return; } if (m_colorCodeStage == 1) { if (m_activeColor != DEFAULT) this->set_color (m_activeColor, false); if (m_boldActive) m_data << RLINE_OFF_BOLD; if (ch >= 'a' and ch <= 'v' and ch != 'l') { auto colorInfo = g_colorCodes[ch - 'a']; m_activeColor = colorInfo.color; m_boldActive = colorInfo.bold; assert (m_activeColor < 8); this->set_color (m_activeColor, true); if (m_boldActive) m_data << RLINE_ON_BOLD; } m_colorCodeStage = 0; return; } if (isprint (ch)) { m_string += ch; m_data << int (ch); ++m_length; } } // ------------------------------------------------------------------------------------------------- // METHOD RendererLine::set_color (Color a, bool on) -> void { switch (a) { case BLACK: m_data << (on ? RLINE_ON_BLACK : RLINE_OFF_BLACK); break; case RED: m_data << (on ? RLINE_ON_RED : RLINE_OFF_RED); break; case GREEN: m_data << (on ? RLINE_ON_GREEN : RLINE_OFF_GREEN); break; case YELLOW: m_data << (on ? RLINE_ON_YELLOW : RLINE_OFF_YELLOW); break; case BLUE: m_data << (on ? RLINE_ON_BLUE : RLINE_OFF_BLUE); break; case MAGENTA: m_data << (on ? RLINE_ON_MAGENTA : RLINE_OFF_MAGENTA); break; case CYAN: m_data << (on ? RLINE_ON_CYAN : RLINE_OFF_CYAN); break; case WHITE: m_data << (on ? RLINE_ON_WHITE : RLINE_OFF_WHITE); break; case NUM_COLORS: case DEFAULT: assert (false); break; } } // ------------------------------------------------------------------------------------------------- // How many rows does this line take up? // METHOD RendererLine::rows (int cols) const -> int { int rows = length() / cols; if (length() % cols != 0) rows++; return max (rows, 1); } // ------------------------------------------------------------------------------------------------- // FUNCTION Interface::tab_complete (const String& part, const String& complete) -> void { String& input = mutable_current_input(); if (input.starts_with (part)) { input.replace (0, part.length(), complete); g_cursor = complete.length(); g_needInputRender = true; } }