From 27db92925261ed6646d0a1c0512711ab3aeb5fb8 Mon Sep 17 00:00:00 2001 From: est31 Date: Mon, 30 May 2016 23:27:48 +1000 Subject: Add minetest.check_password_entry callback Gives a convenient way to check a player's password. This entirely bypasses the SRP protocol, so should be used with great care. This function is not intended to be used in-game, but solely by external protocols, where no authentication of the minetest engine is provided, and also only for protocols, in which the user already gives the server the plaintext password. Examples for good use are the classical http form, or irc, an example for a bad use is a password change dialog inside formspec. Users should be aware that they lose the advantages of the SRP protocol if they enter their passwords for servers outside the normal entry box, like in in-game formspec menus, or through irc /msg s, This patch also fixes an auth.h mistake which has mixed up the order of params inside the decode_srp_verifier_and_salt function. Zeno-: Added errorstream message for invalid format when I committed --- src/util/auth.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/util') diff --git a/src/util/auth.h b/src/util/auth.h index 1fd6ab453..7cdc7d74d 100644 --- a/src/util/auth.h +++ b/src/util/auth.h @@ -45,6 +45,6 @@ std::string encode_srp_verifier(const std::string &verifier, /// Reads the DB-formatted SRP verifier and gets the verifier /// and salt components. bool decode_srp_verifier_and_salt(const std::string &encoded, - std::string *salt, std::string *bytes_v); + std::string *verifier, std::string *salt); #endif -- cgit v1.2.3 From 1d40385d4aacf0cbea4b19ff06940e8c9bebaf47 Mon Sep 17 00:00:00 2001 From: TriBlade9 Date: Fri, 16 Jan 2015 14:54:26 +0800 Subject: Colored chat working as expected for both freetype and non-freetype builds. @nerzhul improvements * Add unit tests * Fix coding style * move guiChatConsole.hpp to client/ --- builtin/game/chatcommands.lua | 2 +- builtin/game/misc.lua | 17 ++ src/chat.cpp | 29 +- src/chat.h | 6 +- src/client/CMakeLists.txt | 1 + src/client/guiChatConsole.cpp | 664 ++++++++++++++++++++++++++++++++++++++++++ src/client/guiChatConsole.h | 138 +++++++++ src/game.cpp | 14 +- src/guiChatConsole.cpp | 649 ----------------------------------------- src/guiChatConsole.h | 138 --------- src/util/CMakeLists.txt | 10 + src/util/coloredstring.cpp | 68 +++++ src/util/coloredstring.h | 44 +++ src/util/statictext.cpp | 654 +++++++++++++++++++++++++++++++++++++++++ src/util/statictext.h | 150 ++++++++++ 15 files changed, 1777 insertions(+), 807 deletions(-) create mode 100644 src/client/guiChatConsole.cpp create mode 100644 src/client/guiChatConsole.h delete mode 100644 src/guiChatConsole.cpp delete mode 100644 src/guiChatConsole.h create mode 100644 src/util/coloredstring.cpp create mode 100644 src/util/coloredstring.h create mode 100644 src/util/statictext.cpp create mode 100644 src/util/statictext.h (limited to 'src/util') diff --git a/builtin/game/chatcommands.lua b/builtin/game/chatcommands.lua index 3350140ee..2627559a5 100644 --- a/builtin/game/chatcommands.lua +++ b/builtin/game/chatcommands.lua @@ -102,7 +102,7 @@ core.register_chatcommand("help", { description = "Get help for commands or list privileges", func = function(name, param) local function format_help_line(cmd, def) - local msg = "/"..cmd + local msg = core.colorize("00ffff", "/"..cmd) if def.params and def.params ~= "" then msg = msg .. " " .. def.params end diff --git a/builtin/game/misc.lua b/builtin/game/misc.lua index de41cfc91..8d5c80216 100644 --- a/builtin/game/misc.lua +++ b/builtin/game/misc.lua @@ -197,3 +197,20 @@ function core.http_add_fetch(httpenv) return httpenv end + +function core.get_color_escape_sequence(color) + --if string.len(color) == 3 then + -- local r = string.sub(color, 1, 1) + -- local g = string.sub(color, 2, 2) + -- local b = string.sub(color, 3, 3) + -- color = r .. r .. g .. g .. b .. b + --end + + --assert(#color == 6, "Color must be six characters in length.") + --return "\v" .. color + return "\v(color;" .. color .. ")" +end + +function core.colorize(color, message) + return core.get_color_escape_sequence(color) .. message .. core.get_color_escape_sequence("ffffff") +end diff --git a/src/chat.cpp b/src/chat.cpp index cebe31225..958389df5 100644 --- a/src/chat.cpp +++ b/src/chat.cpp @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "chat.h" #include "debug.h" +#include "config.h" #include "util/strfnd.h" #include #include @@ -251,8 +252,7 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, u32 hanging_indentation = 0; // Format the sender name and produce fragments - if (!line.name.empty()) - { + if (!line.name.empty()) { temp_frag.text = L"<"; temp_frag.column = 0; //temp_frag.bold = 0; @@ -267,28 +267,28 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, next_frags.push_back(temp_frag); } + std::wstring name_sanitized = removeEscapes(line.name); + // Choose an indentation level - if (line.name.empty()) - { + if (line.name.empty()) { // Server messages hanging_indentation = 0; } - else if (line.name.size() + 3 <= cols/2) - { + else if (name_sanitized.size() + 3 <= cols/2) { // Names shorter than about half the console width hanging_indentation = line.name.size() + 3; } - else - { + else { // Very long names hanging_indentation = 2; } + ColoredString line_text(line.text); next_line.first = true; bool text_processing = false; // Produce fragments and layout them into lines - while (!next_frags.empty() || in_pos < line.text.size()) + while (!next_frags.empty() || in_pos < line_text.size()) { // Layout fragments into lines while (!next_frags.empty()) @@ -326,9 +326,9 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, } // Produce fragment - if (in_pos < line.text.size()) + if (in_pos < line_text.size()) { - u32 remaining_in_input = line.text.size() - in_pos; + u32 remaining_in_input = line_text.size() - in_pos; u32 remaining_in_output = cols - out_column; // Determine a fragment length <= the minimum of @@ -338,14 +338,14 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, while (frag_length < remaining_in_input && frag_length < remaining_in_output) { - if (isspace(line.text[in_pos + frag_length])) + if (isspace(line_text[in_pos + frag_length])) space_pos = frag_length; ++frag_length; } if (space_pos != 0 && frag_length < remaining_in_input) frag_length = space_pos + 1; - temp_frag.text = line.text.substr(in_pos, frag_length); + temp_frag.text = line_text.substr(in_pos, frag_length); temp_frag.column = 0; //temp_frag.bold = 0; next_frags.push_back(temp_frag); @@ -686,9 +686,6 @@ ChatBackend::~ChatBackend() void ChatBackend::addMessage(std::wstring name, std::wstring text) { - name = unescape_enriched(name); - text = unescape_enriched(text); - // Note: A message may consist of multiple lines, for example the MOTD. WStrfnd fnd(text); while (!fnd.at_end()) diff --git a/src/chat.h b/src/chat.h index db4146d35..661cafc82 100644 --- a/src/chat.h +++ b/src/chat.h @@ -20,11 +20,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef CHAT_HEADER #define CHAT_HEADER -#include "irrlichttypes.h" #include #include #include +#include "irrlichttypes.h" +#include "util/coloredstring.h" + // Chat console related classes struct ChatLine @@ -34,7 +36,7 @@ struct ChatLine // name of sending player, or empty if sent by server std::wstring name; // message text - std::wstring text; + ColoredString text; ChatLine(std::wstring a_name, std::wstring a_text): age(0.0), diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index a1ec37fe3..bcf114760 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -1,5 +1,6 @@ set(client_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/clientlauncher.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/guiChatConsole.cpp ${CMAKE_CURRENT_SOURCE_DIR}/tile.cpp PARENT_SCOPE ) diff --git a/src/client/guiChatConsole.cpp b/src/client/guiChatConsole.cpp new file mode 100644 index 000000000..d8837556a --- /dev/null +++ b/src/client/guiChatConsole.cpp @@ -0,0 +1,664 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiChatConsole.h" +#include "chat.h" +#include "client.h" +#include "debug.h" +#include "gettime.h" +#include "keycode.h" +#include "settings.h" +#include "porting.h" +#include "client/tile.h" +#include "fontengine.h" +#include "log.h" +#include "gettext.h" +#include + +#if USE_FREETYPE + #include "xCGUITTFont.h" +#endif + +inline u32 clamp_u8(s32 value) +{ + return (u32) MYMIN(MYMAX(value, 0), 255); +} + + +GUIChatConsole::GUIChatConsole( + gui::IGUIEnvironment* env, + gui::IGUIElement* parent, + s32 id, + ChatBackend* backend, + Client* client, + IMenuManager* menumgr +): + IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, + core::rect(0,0,100,100)), + m_chat_backend(backend), + m_client(client), + m_menumgr(menumgr), + m_screensize(v2u32(0,0)), + m_animate_time_old(0), + m_open(false), + m_close_on_enter(false), + m_height(0), + m_desired_height(0), + m_desired_height_fraction(0.0), + m_height_speed(5.0), + m_open_inhibited(0), + m_cursor_blink(0.0), + m_cursor_blink_speed(0.0), + m_cursor_height(0.0), + m_background(NULL), + m_background_color(255, 0, 0, 0), + m_font(NULL), + m_fontsize(0, 0) +{ + m_animate_time_old = getTimeMs(); + + // load background settings + s32 console_alpha = g_settings->getS32("console_alpha"); + m_background_color.setAlpha(clamp_u8(console_alpha)); + + // load the background texture depending on settings + ITextureSource *tsrc = client->getTextureSource(); + if (tsrc->isKnownSourceImage("background_chat.jpg")) { + m_background = tsrc->getTexture("background_chat.jpg"); + m_background_color.setRed(255); + m_background_color.setGreen(255); + m_background_color.setBlue(255); + } else { + v3f console_color = g_settings->getV3F("console_color"); + m_background_color.setRed(clamp_u8(myround(console_color.X))); + m_background_color.setGreen(clamp_u8(myround(console_color.Y))); + m_background_color.setBlue(clamp_u8(myround(console_color.Z))); + } + + m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); + + if (m_font == NULL) + { + errorstream << "GUIChatConsole: Unable to load mono font "; + } + else + { + core::dimension2d dim = m_font->getDimension(L"M"); + m_fontsize = v2u32(dim.Width, dim.Height); + m_font->grab(); + } + m_fontsize.X = MYMAX(m_fontsize.X, 1); + m_fontsize.Y = MYMAX(m_fontsize.Y, 1); + + // set default cursor options + setCursor(true, true, 2.0, 0.1); +} + +GUIChatConsole::~GUIChatConsole() +{ + if (m_font) + m_font->drop(); +} + +void GUIChatConsole::openConsole(f32 height) +{ + m_open = true; + m_desired_height_fraction = height; + m_desired_height = height * m_screensize.Y; + reformatConsole(); + m_animate_time_old = getTimeMs(); + IGUIElement::setVisible(true); + Environment->setFocus(this); + m_menumgr->createdMenu(this); +} + +bool GUIChatConsole::isOpen() const +{ + return m_open; +} + +bool GUIChatConsole::isOpenInhibited() const +{ + return m_open_inhibited > 0; +} + +void GUIChatConsole::closeConsole() +{ + m_open = false; + Environment->removeFocus(this); + m_menumgr->deletingMenu(this); +} + +void GUIChatConsole::closeConsoleAtOnce() +{ + closeConsole(); + m_height = 0; + recalculateConsolePosition(); +} + +f32 GUIChatConsole::getDesiredHeight() const +{ + return m_desired_height_fraction; +} + +void GUIChatConsole::replaceAndAddToHistory(std::wstring line) +{ + ChatPrompt& prompt = m_chat_backend->getPrompt(); + prompt.addToHistory(prompt.getLine()); + prompt.replace(line); +} + + +void GUIChatConsole::setCursor( + bool visible, bool blinking, f32 blink_speed, f32 relative_height) +{ + if (visible) + { + if (blinking) + { + // leave m_cursor_blink unchanged + m_cursor_blink_speed = blink_speed; + } + else + { + m_cursor_blink = 0x8000; // on + m_cursor_blink_speed = 0.0; + } + } + else + { + m_cursor_blink = 0; // off + m_cursor_blink_speed = 0.0; + } + m_cursor_height = relative_height; +} + +void GUIChatConsole::draw() +{ + if(!IsVisible) + return; + + video::IVideoDriver* driver = Environment->getVideoDriver(); + + // Check screen size + v2u32 screensize = driver->getScreenSize(); + if (screensize != m_screensize) + { + // screen size has changed + // scale current console height to new window size + if (m_screensize.Y != 0) + m_height = m_height * screensize.Y / m_screensize.Y; + m_desired_height = m_desired_height_fraction * m_screensize.Y; + m_screensize = screensize; + reformatConsole(); + } + + // Animation + u32 now = getTimeMs(); + animate(now - m_animate_time_old); + m_animate_time_old = now; + + // Draw console elements if visible + if (m_height > 0) + { + drawBackground(); + drawText(); + drawPrompt(); + } + + gui::IGUIElement::draw(); +} + +void GUIChatConsole::reformatConsole() +{ + s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) + s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt + if (cols <= 0 || rows <= 0) + cols = rows = 0; + m_chat_backend->reformat(cols, rows); +} + +void GUIChatConsole::recalculateConsolePosition() +{ + core::rect rect(0, 0, m_screensize.X, m_height); + DesiredRect = rect; + recalculateAbsolutePosition(false); +} + +void GUIChatConsole::animate(u32 msec) +{ + // animate the console height + s32 goal = m_open ? m_desired_height : 0; + + // Set invisible if close animation finished (reset by openConsole) + // This function (animate()) is never called once its visibility becomes false so do not + // actually set visible to false before the inhibited period is over + if (!m_open && m_height == 0 && m_open_inhibited == 0) + IGUIElement::setVisible(false); + + if (m_height != goal) + { + s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); + if (max_change == 0) + max_change = 1; + + if (m_height < goal) + { + // increase height + if (m_height + max_change < goal) + m_height += max_change; + else + m_height = goal; + } + else + { + // decrease height + if (m_height > goal + max_change) + m_height -= max_change; + else + m_height = goal; + } + + recalculateConsolePosition(); + } + + // blink the cursor + if (m_cursor_blink_speed != 0.0) + { + u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); + if (blink_increase == 0) + blink_increase = 1; + m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff); + } + + // decrease open inhibit counter + if (m_open_inhibited > msec) + m_open_inhibited -= msec; + else + m_open_inhibited = 0; +} + +void GUIChatConsole::drawBackground() +{ + video::IVideoDriver* driver = Environment->getVideoDriver(); + if (m_background != NULL) + { + core::rect sourcerect(0, -m_height, m_screensize.X, 0); + driver->draw2DImage( + m_background, + v2s32(0, 0), + sourcerect, + &AbsoluteClippingRect, + m_background_color, + false); + } + else + { + driver->draw2DRectangle( + m_background_color, + core::rect(0, 0, m_screensize.X, m_height), + &AbsoluteClippingRect); + } +} + +void GUIChatConsole::drawText() +{ + if (m_font == NULL) + return; + + ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); + for (u32 row = 0; row < buf.getRows(); ++row) + { + const ChatFormattedLine& line = buf.getFormattedLine(row); + if (line.fragments.empty()) + continue; + + s32 line_height = m_fontsize.Y; + s32 y = row * line_height + m_height - m_desired_height; + if (y + line_height < 0) + continue; + + for (u32 i = 0; i < line.fragments.size(); ++i) + { + const ChatFormattedFragment& fragment = line.fragments[i]; + s32 x = (fragment.column + 1) * m_fontsize.X; + core::rect destrect( + x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); + + + #if USE_FREETYPE + // Draw colored text if FreeType is enabled + irr::gui::CGUITTFont *tmp = static_cast(m_font); + tmp->draw( + fragment.text.c_str(), + destrect, + fragment.text.getColors(), + false, + false, + &AbsoluteClippingRect); + #else + // Otherwise use standard text + m_font->draw( + fragment.text.c_str(), + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); + #endif + } + } +} + +void GUIChatConsole::drawPrompt() +{ + if (m_font == NULL) + return; + + u32 row = m_chat_backend->getConsoleBuffer().getRows(); + s32 line_height = m_fontsize.Y; + s32 y = row * line_height + m_height - m_desired_height; + + ChatPrompt& prompt = m_chat_backend->getPrompt(); + std::wstring prompt_text = prompt.getVisiblePortion(); + + // FIXME Draw string at once, not character by character + // That will only work with the cursor once we have a monospace font + for (u32 i = 0; i < prompt_text.size(); ++i) + { + wchar_t ws[2] = {prompt_text[i], 0}; + s32 x = (1 + i) * m_fontsize.X; + core::rect destrect( + x, y, x + m_fontsize.X, y + m_fontsize.Y); + m_font->draw( + ws, + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); + } + + // Draw the cursor during on periods + if ((m_cursor_blink & 0x8000) != 0) + { + s32 cursor_pos = prompt.getVisibleCursorPosition(); + if (cursor_pos >= 0) + { + s32 cursor_len = prompt.getCursorLength(); + video::IVideoDriver* driver = Environment->getVideoDriver(); + s32 x = (1 + cursor_pos) * m_fontsize.X; + core::rect destrect( + x, + y + m_fontsize.Y * (1.0 - m_cursor_height), + x + m_fontsize.X * MYMAX(cursor_len, 1), + y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) + ); + video::SColor cursor_color(255,255,255,255); + driver->draw2DRectangle( + cursor_color, + destrect, + &AbsoluteClippingRect); + } + } + +} + +bool GUIChatConsole::OnEvent(const SEvent& event) +{ + + ChatPrompt &prompt = m_chat_backend->getPrompt(); + + if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) + { + // Key input + if(KeyPress(event.KeyInput) == getKeySetting("keymap_console")) + { + closeConsole(); + + // inhibit open so the_game doesn't reopen immediately + m_open_inhibited = 50; + m_close_on_enter = false; + return true; + } + else if(event.KeyInput.Key == KEY_ESCAPE) + { + closeConsoleAtOnce(); + m_close_on_enter = false; + // inhibit open so the_game doesn't reopen immediately + m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" + return true; + } + else if(event.KeyInput.Key == KEY_PRIOR) + { + m_chat_backend->scrollPageUp(); + return true; + } + else if(event.KeyInput.Key == KEY_NEXT) + { + m_chat_backend->scrollPageDown(); + return true; + } + else if(event.KeyInput.Key == KEY_RETURN) + { + prompt.addToHistory(prompt.getLine()); + std::wstring text = prompt.replace(L""); + m_client->typeChatMessage(text); + if (m_close_on_enter) { + closeConsoleAtOnce(); + m_close_on_enter = false; + } + return true; + } + else if(event.KeyInput.Key == KEY_UP) + { + // Up pressed + // Move back in history + prompt.historyPrev(); + return true; + } + else if(event.KeyInput.Key == KEY_DOWN) + { + // Down pressed + // Move forward in history + prompt.historyNext(); + return true; + } + else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) + { + // Left/right pressed + // Move/select character/word to the left depending on control and shift keys + ChatPrompt::CursorOp op = event.KeyInput.Shift ? + ChatPrompt::CURSOROP_SELECT : + ChatPrompt::CURSOROP_MOVE; + ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? + ChatPrompt::CURSOROP_DIR_LEFT : + ChatPrompt::CURSOROP_DIR_RIGHT; + ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation(op, dir, scope); + return true; + } + else if(event.KeyInput.Key == KEY_HOME) + { + // Home pressed + // move to beginning of line + prompt.cursorOperation( + ChatPrompt::CURSOROP_MOVE, + ChatPrompt::CURSOROP_DIR_LEFT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_END) + { + // End pressed + // move to end of line + prompt.cursorOperation( + ChatPrompt::CURSOROP_MOVE, + ChatPrompt::CURSOROP_DIR_RIGHT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_BACK) + { + // Backspace or Ctrl-Backspace pressed + // delete character / word to the left + ChatPrompt::CursorOpScope scope = + event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, + scope); + return true; + } + else if(event.KeyInput.Key == KEY_DELETE) + { + // Delete or Ctrl-Delete pressed + // delete character / word to the right + ChatPrompt::CursorOpScope scope = + event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_RIGHT, + scope); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) + { + // Ctrl-A pressed + // Select all text + prompt.cursorOperation( + ChatPrompt::CURSOROP_SELECT, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) + { + // Ctrl-C pressed + // Copy text to clipboard + if (prompt.getCursorLength() <= 0) + return true; + std::wstring wselected = prompt.getSelection(); + std::string selected(wselected.begin(), wselected.end()); + Environment->getOSOperator()->copyToClipboard(selected.c_str()); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) + { + // Ctrl-V pressed + // paste text from clipboard + if (prompt.getCursorLength() > 0) { + // Delete selected section of text + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_SELECTION); + } + IOSOperator *os_operator = Environment->getOSOperator(); + const c8 *text = os_operator->getTextFromClipboard(); + if (!text) + return true; + std::basic_string str((const unsigned char*)text); + prompt.input(std::wstring(str.begin(), str.end())); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) + { + // Ctrl-X pressed + // Cut text to clipboard + if (prompt.getCursorLength() <= 0) + return true; + std::wstring wselected = prompt.getSelection(); + std::string selected(wselected.begin(), wselected.end()); + Environment->getOSOperator()->copyToClipboard(selected.c_str()); + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_SELECTION); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) + { + // Ctrl-U pressed + // kill line to left end + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) + { + // Ctrl-K pressed + // kill line to right end + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_RIGHT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_TAB) + { + // Tab or Shift-Tab pressed + // Nick completion + std::list names = m_client->getConnectedPlayerNames(); + bool backwards = event.KeyInput.Shift; + prompt.nickCompletion(names, backwards); + return true; + } + else if(event.KeyInput.Char != 0 && !event.KeyInput.Control) + { + #if (defined(linux) || defined(__linux)) + wchar_t wc = L'_'; + mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); + prompt.input(wc); + #else + prompt.input(event.KeyInput.Char); + #endif + return true; + } + } + else if(event.EventType == EET_MOUSE_INPUT_EVENT) + { + if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) + { + s32 rows = myround(-3.0 * event.MouseInput.Wheel); + m_chat_backend->scroll(rows); + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + +void GUIChatConsole::setVisible(bool visible) +{ + m_open = visible; + IGUIElement::setVisible(visible); + if (!visible) { + m_height = 0; + recalculateConsolePosition(); + } +} + diff --git a/src/client/guiChatConsole.h b/src/client/guiChatConsole.h new file mode 100644 index 000000000..3013a1d31 --- /dev/null +++ b/src/client/guiChatConsole.h @@ -0,0 +1,138 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GUICHATCONSOLE_HEADER +#define GUICHATCONSOLE_HEADER + +#include "irrlichttypes_extrabloated.h" +#include "modalMenu.h" +#include "chat.h" +#include "config.h" + +class Client; + +class GUIChatConsole : public gui::IGUIElement +{ +public: + GUIChatConsole(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, + s32 id, + ChatBackend* backend, + Client* client, + IMenuManager* menumgr); + virtual ~GUIChatConsole(); + + // Open the console (height = desired fraction of screen size) + // This doesn't open immediately but initiates an animation. + // You should call isOpenInhibited() before this. + void openConsole(f32 height); + + bool isOpen() const; + + // Check if the console should not be opened at the moment + // This is to avoid reopening the console immediately after closing + bool isOpenInhibited() const; + // Close the console, equivalent to openConsole(0). + // This doesn't close immediately but initiates an animation. + void closeConsole(); + // Close the console immediately, without animation. + void closeConsoleAtOnce(); + // Set whether to close the console after the user presses enter. + void setCloseOnEnter(bool close) { m_close_on_enter = close; } + + // Return the desired height (fraction of screen size) + // Zero if the console is closed or getting closed + f32 getDesiredHeight() const; + + // Replace actual line when adding the actual to the history (if there is any) + void replaceAndAddToHistory(std::wstring line); + + // Change how the cursor looks + void setCursor( + bool visible, + bool blinking = false, + f32 blink_speed = 1.0, + f32 relative_height = 1.0); + + // Irrlicht draw method + virtual void draw(); + + bool canTakeFocus(gui::IGUIElement* element) { return false; } + + virtual bool OnEvent(const SEvent& event); + + virtual void setVisible(bool visible); + +private: + void reformatConsole(); + void recalculateConsolePosition(); + + // These methods are called by draw + void animate(u32 msec); + void drawBackground(); + void drawText(); + void drawPrompt(); + +private: + ChatBackend* m_chat_backend; + Client* m_client; + IMenuManager* m_menumgr; + + // current screen size + v2u32 m_screensize; + + // used to compute how much time passed since last animate() + u32 m_animate_time_old; + + // should the console be opened or closed? + bool m_open; + // should it close after you press enter? + bool m_close_on_enter; + // current console height [pixels] + s32 m_height; + // desired height [pixels] + f32 m_desired_height; + // desired height [screen height fraction] + f32 m_desired_height_fraction; + // console open/close animation speed [screen height fraction / second] + f32 m_height_speed; + // if nonzero, opening the console is inhibited [milliseconds] + u32 m_open_inhibited; + + // cursor blink frame (16-bit value) + // cursor is off during [0,32767] and on during [32768,65535] + u32 m_cursor_blink; + // cursor blink speed [on/off toggles / second] + f32 m_cursor_blink_speed; + // cursor height [line height] + f32 m_cursor_height; + + // background texture + video::ITexture* m_background; + // background color (including alpha) + video::SColor m_background_color; + + // font + gui::IGUIFont* m_font; + v2u32 m_fontsize; +}; + + +#endif + diff --git a/src/game.cpp b/src/game.cpp index c5211a042..71a04aef5 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -34,7 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "filesys.h" #include "gettext.h" -#include "guiChatConsole.h" +#include "client/guiChatConsole.h" #include "guiFormSpecMenu.h" #include "guiKeyChangeMenu.h" #include "guiPasswordChange.h" @@ -59,6 +59,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "minimap.h" #include "mapblock_mesh.h" +#if USE_FREETYPE + #include "util/statictext.h" +#endif + #include "sound.h" #if USE_SOUND @@ -2239,12 +2243,20 @@ bool Game::initGui() false, false, guiroot); guitext_status->setVisible(false); +#if USE_FREETYPE + // Colored chat support when using FreeType + guitext_chat = new gui::StaticText(L"", false, guienv, guiroot, -1, core::rect(0, 0, 0, 0), false); + guitext_chat->setWordWrap(true); + guitext_chat->drop(); +#else + // Standard chat when FreeType is disabled // Chat text guitext_chat = guienv->addStaticText( L"", core::rect(0, 0, 0, 0), //false, false); // Disable word wrap as of now false, true, guiroot); +#endif // Remove stale "recent" chat messages from previous connections chat_backend->clearRecentChat(); diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp deleted file mode 100644 index 17a1689c7..000000000 --- a/src/guiChatConsole.cpp +++ /dev/null @@ -1,649 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#include "guiChatConsole.h" -#include "chat.h" -#include "client.h" -#include "debug.h" -#include "gettime.h" -#include "keycode.h" -#include "settings.h" -#include "porting.h" -#include "client/tile.h" -#include "fontengine.h" -#include "log.h" -#include "gettext.h" -#include - -#if USE_FREETYPE -#include "xCGUITTFont.h" -#endif - -inline u32 clamp_u8(s32 value) -{ - return (u32) MYMIN(MYMAX(value, 0), 255); -} - - -GUIChatConsole::GUIChatConsole( - gui::IGUIEnvironment* env, - gui::IGUIElement* parent, - s32 id, - ChatBackend* backend, - Client* client, - IMenuManager* menumgr -): - IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, - core::rect(0,0,100,100)), - m_chat_backend(backend), - m_client(client), - m_menumgr(menumgr), - m_screensize(v2u32(0,0)), - m_animate_time_old(0), - m_open(false), - m_close_on_enter(false), - m_height(0), - m_desired_height(0), - m_desired_height_fraction(0.0), - m_height_speed(5.0), - m_open_inhibited(0), - m_cursor_blink(0.0), - m_cursor_blink_speed(0.0), - m_cursor_height(0.0), - m_background(NULL), - m_background_color(255, 0, 0, 0), - m_font(NULL), - m_fontsize(0, 0) -{ - m_animate_time_old = getTimeMs(); - - // load background settings - s32 console_alpha = g_settings->getS32("console_alpha"); - m_background_color.setAlpha(clamp_u8(console_alpha)); - - // load the background texture depending on settings - ITextureSource *tsrc = client->getTextureSource(); - if (tsrc->isKnownSourceImage("background_chat.jpg")) { - m_background = tsrc->getTexture("background_chat.jpg"); - m_background_color.setRed(255); - m_background_color.setGreen(255); - m_background_color.setBlue(255); - } else { - v3f console_color = g_settings->getV3F("console_color"); - m_background_color.setRed(clamp_u8(myround(console_color.X))); - m_background_color.setGreen(clamp_u8(myround(console_color.Y))); - m_background_color.setBlue(clamp_u8(myround(console_color.Z))); - } - - m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); - - if (m_font == NULL) - { - errorstream << "GUIChatConsole: Unable to load mono font "; - } - else - { - core::dimension2d dim = m_font->getDimension(L"M"); - m_fontsize = v2u32(dim.Width, dim.Height); - m_font->grab(); - } - m_fontsize.X = MYMAX(m_fontsize.X, 1); - m_fontsize.Y = MYMAX(m_fontsize.Y, 1); - - // set default cursor options - setCursor(true, true, 2.0, 0.1); -} - -GUIChatConsole::~GUIChatConsole() -{ - if (m_font) - m_font->drop(); -} - -void GUIChatConsole::openConsole(f32 height) -{ - m_open = true; - m_desired_height_fraction = height; - m_desired_height = height * m_screensize.Y; - reformatConsole(); - m_animate_time_old = getTimeMs(); - IGUIElement::setVisible(true); - Environment->setFocus(this); - m_menumgr->createdMenu(this); -} - -bool GUIChatConsole::isOpen() const -{ - return m_open; -} - -bool GUIChatConsole::isOpenInhibited() const -{ - return m_open_inhibited > 0; -} - -void GUIChatConsole::closeConsole() -{ - m_open = false; - Environment->removeFocus(this); - m_menumgr->deletingMenu(this); -} - -void GUIChatConsole::closeConsoleAtOnce() -{ - closeConsole(); - m_height = 0; - recalculateConsolePosition(); -} - -f32 GUIChatConsole::getDesiredHeight() const -{ - return m_desired_height_fraction; -} - -void GUIChatConsole::replaceAndAddToHistory(std::wstring line) -{ - ChatPrompt& prompt = m_chat_backend->getPrompt(); - prompt.addToHistory(prompt.getLine()); - prompt.replace(line); -} - - -void GUIChatConsole::setCursor( - bool visible, bool blinking, f32 blink_speed, f32 relative_height) -{ - if (visible) - { - if (blinking) - { - // leave m_cursor_blink unchanged - m_cursor_blink_speed = blink_speed; - } - else - { - m_cursor_blink = 0x8000; // on - m_cursor_blink_speed = 0.0; - } - } - else - { - m_cursor_blink = 0; // off - m_cursor_blink_speed = 0.0; - } - m_cursor_height = relative_height; -} - -void GUIChatConsole::draw() -{ - if(!IsVisible) - return; - - video::IVideoDriver* driver = Environment->getVideoDriver(); - - // Check screen size - v2u32 screensize = driver->getScreenSize(); - if (screensize != m_screensize) - { - // screen size has changed - // scale current console height to new window size - if (m_screensize.Y != 0) - m_height = m_height * screensize.Y / m_screensize.Y; - m_desired_height = m_desired_height_fraction * m_screensize.Y; - m_screensize = screensize; - reformatConsole(); - } - - // Animation - u32 now = getTimeMs(); - animate(now - m_animate_time_old); - m_animate_time_old = now; - - // Draw console elements if visible - if (m_height > 0) - { - drawBackground(); - drawText(); - drawPrompt(); - } - - gui::IGUIElement::draw(); -} - -void GUIChatConsole::reformatConsole() -{ - s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) - s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt - if (cols <= 0 || rows <= 0) - cols = rows = 0; - m_chat_backend->reformat(cols, rows); -} - -void GUIChatConsole::recalculateConsolePosition() -{ - core::rect rect(0, 0, m_screensize.X, m_height); - DesiredRect = rect; - recalculateAbsolutePosition(false); -} - -void GUIChatConsole::animate(u32 msec) -{ - // animate the console height - s32 goal = m_open ? m_desired_height : 0; - - // Set invisible if close animation finished (reset by openConsole) - // This function (animate()) is never called once its visibility becomes false so do not - // actually set visible to false before the inhibited period is over - if (!m_open && m_height == 0 && m_open_inhibited == 0) - IGUIElement::setVisible(false); - - if (m_height != goal) - { - s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); - if (max_change == 0) - max_change = 1; - - if (m_height < goal) - { - // increase height - if (m_height + max_change < goal) - m_height += max_change; - else - m_height = goal; - } - else - { - // decrease height - if (m_height > goal + max_change) - m_height -= max_change; - else - m_height = goal; - } - - recalculateConsolePosition(); - } - - // blink the cursor - if (m_cursor_blink_speed != 0.0) - { - u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); - if (blink_increase == 0) - blink_increase = 1; - m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff); - } - - // decrease open inhibit counter - if (m_open_inhibited > msec) - m_open_inhibited -= msec; - else - m_open_inhibited = 0; -} - -void GUIChatConsole::drawBackground() -{ - video::IVideoDriver* driver = Environment->getVideoDriver(); - if (m_background != NULL) - { - core::rect sourcerect(0, -m_height, m_screensize.X, 0); - driver->draw2DImage( - m_background, - v2s32(0, 0), - sourcerect, - &AbsoluteClippingRect, - m_background_color, - false); - } - else - { - driver->draw2DRectangle( - m_background_color, - core::rect(0, 0, m_screensize.X, m_height), - &AbsoluteClippingRect); - } -} - -void GUIChatConsole::drawText() -{ - if (m_font == NULL) - return; - - ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); - for (u32 row = 0; row < buf.getRows(); ++row) - { - const ChatFormattedLine& line = buf.getFormattedLine(row); - if (line.fragments.empty()) - continue; - - s32 line_height = m_fontsize.Y; - s32 y = row * line_height + m_height - m_desired_height; - if (y + line_height < 0) - continue; - - for (u32 i = 0; i < line.fragments.size(); ++i) - { - const ChatFormattedFragment& fragment = line.fragments[i]; - s32 x = (fragment.column + 1) * m_fontsize.X; - core::rect destrect( - x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); - m_font->draw( - fragment.text.c_str(), - destrect, - video::SColor(255, 255, 255, 255), - false, - false, - &AbsoluteClippingRect); - } - } -} - -void GUIChatConsole::drawPrompt() -{ - if (m_font == NULL) - return; - - u32 row = m_chat_backend->getConsoleBuffer().getRows(); - s32 line_height = m_fontsize.Y; - s32 y = row * line_height + m_height - m_desired_height; - - ChatPrompt& prompt = m_chat_backend->getPrompt(); - std::wstring prompt_text = prompt.getVisiblePortion(); - - // FIXME Draw string at once, not character by character - // That will only work with the cursor once we have a monospace font - for (u32 i = 0; i < prompt_text.size(); ++i) - { - wchar_t ws[2] = {prompt_text[i], 0}; - s32 x = (1 + i) * m_fontsize.X; - core::rect destrect( - x, y, x + m_fontsize.X, y + m_fontsize.Y); - m_font->draw( - ws, - destrect, - video::SColor(255, 255, 255, 255), - false, - false, - &AbsoluteClippingRect); - } - - // Draw the cursor during on periods - if ((m_cursor_blink & 0x8000) != 0) - { - s32 cursor_pos = prompt.getVisibleCursorPosition(); - if (cursor_pos >= 0) - { - s32 cursor_len = prompt.getCursorLength(); - video::IVideoDriver* driver = Environment->getVideoDriver(); - s32 x = (1 + cursor_pos) * m_fontsize.X; - core::rect destrect( - x, - y + m_fontsize.Y * (1.0 - m_cursor_height), - x + m_fontsize.X * MYMAX(cursor_len, 1), - y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) - ); - video::SColor cursor_color(255,255,255,255); - driver->draw2DRectangle( - cursor_color, - destrect, - &AbsoluteClippingRect); - } - } - -} - -bool GUIChatConsole::OnEvent(const SEvent& event) -{ - - ChatPrompt &prompt = m_chat_backend->getPrompt(); - - if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) - { - // Key input - if(KeyPress(event.KeyInput) == getKeySetting("keymap_console")) - { - closeConsole(); - - // inhibit open so the_game doesn't reopen immediately - m_open_inhibited = 50; - m_close_on_enter = false; - return true; - } - else if(event.KeyInput.Key == KEY_ESCAPE) - { - closeConsoleAtOnce(); - m_close_on_enter = false; - // inhibit open so the_game doesn't reopen immediately - m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" - return true; - } - else if(event.KeyInput.Key == KEY_PRIOR) - { - m_chat_backend->scrollPageUp(); - return true; - } - else if(event.KeyInput.Key == KEY_NEXT) - { - m_chat_backend->scrollPageDown(); - return true; - } - else if(event.KeyInput.Key == KEY_RETURN) - { - prompt.addToHistory(prompt.getLine()); - std::wstring text = prompt.replace(L""); - m_client->typeChatMessage(text); - if (m_close_on_enter) { - closeConsoleAtOnce(); - m_close_on_enter = false; - } - return true; - } - else if(event.KeyInput.Key == KEY_UP) - { - // Up pressed - // Move back in history - prompt.historyPrev(); - return true; - } - else if(event.KeyInput.Key == KEY_DOWN) - { - // Down pressed - // Move forward in history - prompt.historyNext(); - return true; - } - else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) - { - // Left/right pressed - // Move/select character/word to the left depending on control and shift keys - ChatPrompt::CursorOp op = event.KeyInput.Shift ? - ChatPrompt::CURSOROP_SELECT : - ChatPrompt::CURSOROP_MOVE; - ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? - ChatPrompt::CURSOROP_DIR_LEFT : - ChatPrompt::CURSOROP_DIR_RIGHT; - ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? - ChatPrompt::CURSOROP_SCOPE_WORD : - ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation(op, dir, scope); - return true; - } - else if(event.KeyInput.Key == KEY_HOME) - { - // Home pressed - // move to beginning of line - prompt.cursorOperation( - ChatPrompt::CURSOROP_MOVE, - ChatPrompt::CURSOROP_DIR_LEFT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_END) - { - // End pressed - // move to end of line - prompt.cursorOperation( - ChatPrompt::CURSOROP_MOVE, - ChatPrompt::CURSOROP_DIR_RIGHT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_BACK) - { - // Backspace or Ctrl-Backspace pressed - // delete character / word to the left - ChatPrompt::CursorOpScope scope = - event.KeyInput.Control ? - ChatPrompt::CURSOROP_SCOPE_WORD : - ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, - scope); - return true; - } - else if(event.KeyInput.Key == KEY_DELETE) - { - // Delete or Ctrl-Delete pressed - // delete character / word to the right - ChatPrompt::CursorOpScope scope = - event.KeyInput.Control ? - ChatPrompt::CURSOROP_SCOPE_WORD : - ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_RIGHT, - scope); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) - { - // Ctrl-A pressed - // Select all text - prompt.cursorOperation( - ChatPrompt::CURSOROP_SELECT, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) - { - // Ctrl-C pressed - // Copy text to clipboard - if (prompt.getCursorLength() <= 0) - return true; - std::wstring wselected = prompt.getSelection(); - std::string selected(wselected.begin(), wselected.end()); - Environment->getOSOperator()->copyToClipboard(selected.c_str()); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) - { - // Ctrl-V pressed - // paste text from clipboard - if (prompt.getCursorLength() > 0) { - // Delete selected section of text - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_SELECTION); - } - IOSOperator *os_operator = Environment->getOSOperator(); - const c8 *text = os_operator->getTextFromClipboard(); - if (!text) - return true; - std::basic_string str((const unsigned char*)text); - prompt.input(std::wstring(str.begin(), str.end())); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) - { - // Ctrl-X pressed - // Cut text to clipboard - if (prompt.getCursorLength() <= 0) - return true; - std::wstring wselected = prompt.getSelection(); - std::string selected(wselected.begin(), wselected.end()); - Environment->getOSOperator()->copyToClipboard(selected.c_str()); - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_SELECTION); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) - { - // Ctrl-U pressed - // kill line to left end - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) - { - // Ctrl-K pressed - // kill line to right end - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_RIGHT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_TAB) - { - // Tab or Shift-Tab pressed - // Nick completion - std::list names = m_client->getConnectedPlayerNames(); - bool backwards = event.KeyInput.Shift; - prompt.nickCompletion(names, backwards); - return true; - } - else if(event.KeyInput.Char != 0 && !event.KeyInput.Control) - { - #if (defined(linux) || defined(__linux)) - wchar_t wc = L'_'; - mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); - prompt.input(wc); - #else - prompt.input(event.KeyInput.Char); - #endif - return true; - } - } - else if(event.EventType == EET_MOUSE_INPUT_EVENT) - { - if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) - { - s32 rows = myround(-3.0 * event.MouseInput.Wheel); - m_chat_backend->scroll(rows); - } - } - - return Parent ? Parent->OnEvent(event) : false; -} - -void GUIChatConsole::setVisible(bool visible) -{ - m_open = visible; - IGUIElement::setVisible(visible); - if (!visible) { - m_height = 0; - recalculateConsolePosition(); - } -} - diff --git a/src/guiChatConsole.h b/src/guiChatConsole.h deleted file mode 100644 index 3013a1d31..000000000 --- a/src/guiChatConsole.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#ifndef GUICHATCONSOLE_HEADER -#define GUICHATCONSOLE_HEADER - -#include "irrlichttypes_extrabloated.h" -#include "modalMenu.h" -#include "chat.h" -#include "config.h" - -class Client; - -class GUIChatConsole : public gui::IGUIElement -{ -public: - GUIChatConsole(gui::IGUIEnvironment* env, - gui::IGUIElement* parent, - s32 id, - ChatBackend* backend, - Client* client, - IMenuManager* menumgr); - virtual ~GUIChatConsole(); - - // Open the console (height = desired fraction of screen size) - // This doesn't open immediately but initiates an animation. - // You should call isOpenInhibited() before this. - void openConsole(f32 height); - - bool isOpen() const; - - // Check if the console should not be opened at the moment - // This is to avoid reopening the console immediately after closing - bool isOpenInhibited() const; - // Close the console, equivalent to openConsole(0). - // This doesn't close immediately but initiates an animation. - void closeConsole(); - // Close the console immediately, without animation. - void closeConsoleAtOnce(); - // Set whether to close the console after the user presses enter. - void setCloseOnEnter(bool close) { m_close_on_enter = close; } - - // Return the desired height (fraction of screen size) - // Zero if the console is closed or getting closed - f32 getDesiredHeight() const; - - // Replace actual line when adding the actual to the history (if there is any) - void replaceAndAddToHistory(std::wstring line); - - // Change how the cursor looks - void setCursor( - bool visible, - bool blinking = false, - f32 blink_speed = 1.0, - f32 relative_height = 1.0); - - // Irrlicht draw method - virtual void draw(); - - bool canTakeFocus(gui::IGUIElement* element) { return false; } - - virtual bool OnEvent(const SEvent& event); - - virtual void setVisible(bool visible); - -private: - void reformatConsole(); - void recalculateConsolePosition(); - - // These methods are called by draw - void animate(u32 msec); - void drawBackground(); - void drawText(); - void drawPrompt(); - -private: - ChatBackend* m_chat_backend; - Client* m_client; - IMenuManager* m_menumgr; - - // current screen size - v2u32 m_screensize; - - // used to compute how much time passed since last animate() - u32 m_animate_time_old; - - // should the console be opened or closed? - bool m_open; - // should it close after you press enter? - bool m_close_on_enter; - // current console height [pixels] - s32 m_height; - // desired height [pixels] - f32 m_desired_height; - // desired height [screen height fraction] - f32 m_desired_height_fraction; - // console open/close animation speed [screen height fraction / second] - f32 m_height_speed; - // if nonzero, opening the console is inhibited [milliseconds] - u32 m_open_inhibited; - - // cursor blink frame (16-bit value) - // cursor is off during [0,32767] and on during [32768,65535] - u32 m_cursor_blink; - // cursor blink speed [on/off toggles / second] - f32 m_cursor_blink_speed; - // cursor height [line height] - f32 m_cursor_height; - - // background texture - video::ITexture* m_background; - // background color (including alpha) - video::SColor m_background_color; - - // font - gui::IGUIFont* m_font; - v2u32 m_fontsize; -}; - - -#endif - diff --git a/src/util/CMakeLists.txt b/src/util/CMakeLists.txt index 0e7cbad07..e028a0435 100644 --- a/src/util/CMakeLists.txt +++ b/src/util/CMakeLists.txt @@ -1,7 +1,16 @@ +if(USE_FREETYPE) + set(UTIL_FREETYPEDEP_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/statictext.cpp + ) +else() + set(UTIL_FREETYPEDEP_SRCS ) +endif(USE_FREETYPE) + set(UTIL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/areastore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/auth.cpp ${CMAKE_CURRENT_SOURCE_DIR}/base64.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coloredstring.cpp ${CMAKE_CURRENT_SOURCE_DIR}/directiontables.cpp ${CMAKE_CURRENT_SOURCE_DIR}/numeric.cpp ${CMAKE_CURRENT_SOURCE_DIR}/pointedthing.cpp @@ -11,5 +20,6 @@ set(UTIL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/string.cpp ${CMAKE_CURRENT_SOURCE_DIR}/srp.cpp ${CMAKE_CURRENT_SOURCE_DIR}/timetaker.cpp + ${UTIL_FREETYPEDEP_SRCS} PARENT_SCOPE) diff --git a/src/util/coloredstring.cpp b/src/util/coloredstring.cpp new file mode 100644 index 000000000..7db586550 --- /dev/null +++ b/src/util/coloredstring.cpp @@ -0,0 +1,68 @@ +/* +Copyright (C) 2013 xyz, Ilya Zhuravlev + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "coloredstring.h" +#include "util/string.h" + +ColoredString::ColoredString() +{} + +ColoredString::ColoredString(const std::wstring &string, const std::vector &colors): + m_string(string), + m_colors(colors) +{} + +ColoredString::ColoredString(const std::wstring &s) { + m_string = colorizeText(s, m_colors, SColor(255, 255, 255, 255)); +} + +void ColoredString::operator=(const wchar_t *str) { + m_string = colorizeText(str, m_colors, SColor(255, 255, 255, 255)); +} + +size_t ColoredString::size() const { + return m_string.size(); +} + +ColoredString ColoredString::substr(size_t pos, size_t len) const { + if (pos == m_string.length()) + return ColoredString(); + if (len == std::string::npos || pos + len > m_string.length()) { + return ColoredString( + m_string.substr(pos, std::string::npos), + std::vector(m_colors.begin() + pos, m_colors.end()) + ); + } else { + return ColoredString( + m_string.substr(pos, len), + std::vector(m_colors.begin() + pos, m_colors.begin() + pos + len) + ); + } +} + +const wchar_t *ColoredString::c_str() const { + return m_string.c_str(); +} + +const std::vector &ColoredString::getColors() const { + return m_colors; +} + +const std::wstring &ColoredString::getString() const { + return m_string; +} diff --git a/src/util/coloredstring.h b/src/util/coloredstring.h new file mode 100644 index 000000000..a6d98db30 --- /dev/null +++ b/src/util/coloredstring.h @@ -0,0 +1,44 @@ +/* +Copyright (C) 2013 xyz, Ilya Zhuravlev + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef COLOREDSTRING_HEADER +#define COLOREDSTRING_HEADER + +#include +#include +#include + +using namespace irr::video; + +class ColoredString { +public: + ColoredString(); + ColoredString(const std::wstring &s); + ColoredString(const std::wstring &string, const std::vector &colors); + void operator=(const wchar_t *str); + size_t size() const; + ColoredString substr(size_t pos = 0, size_t len = std::string::npos) const; + const wchar_t *c_str() const; + const std::vector &getColors() const; + const std::wstring &getString() const; +private: + std::wstring m_string; + std::vector m_colors; +}; + +#endif diff --git a/src/util/statictext.cpp b/src/util/statictext.cpp new file mode 100644 index 000000000..b534b560e --- /dev/null +++ b/src/util/statictext.cpp @@ -0,0 +1,654 @@ +// Copyright (C) 2002-2012 Nikolaus Gebhardt +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#include "statictext.h" +#ifdef _IRR_COMPILE_WITH_GUI_ + +//Only compile this if freetype is enabled. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cguittfont/xCGUITTFont.h" +#include "util/string.h" + +namespace irr +{ +namespace gui +{ +//! constructor +StaticText::StaticText(const wchar_t* text, bool border, + IGUIEnvironment* environment, IGUIElement* parent, + s32 id, const core::rect& rectangle, + bool background) +: IGUIStaticText(environment, parent, id, rectangle), + HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), + Border(border), OverrideColorEnabled(false), OverrideBGColorEnabled(false), WordWrap(false), Background(background), + RestrainTextInside(true), RightToLeft(false), + OverrideColor(video::SColor(101,255,255,255)), BGColor(video::SColor(101,210,210,210)), + OverrideFont(0), LastBreakFont(0) +{ + #ifdef _DEBUG + setDebugName("StaticText"); + #endif + + Text = text; + if (environment && environment->getSkin()) + { + BGColor = environment->getSkin()->getColor(gui::EGDC_3D_FACE); + } +} + + +//! destructor +StaticText::~StaticText() +{ + if (OverrideFont) + OverrideFont->drop(); +} + + +//! draws the element and its children +void StaticText::draw() +{ + if (!IsVisible) + return; + + IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + core::rect frameRect(AbsoluteRect); + + // draw background + + if (Background) + { + if ( !OverrideBGColorEnabled ) // skin-colors can change + BGColor = skin->getColor(gui::EGDC_3D_FACE); + + driver->draw2DRectangle(BGColor, frameRect, &AbsoluteClippingRect); + } + + // draw the border + + if (Border) + { + skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); + frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); + } + + // draw the text + if (Text.size()) + { + IGUIFont* font = getActiveFont(); + + if (font) + { + if (!WordWrap) + { + // TODO: add colors here + if (VAlign == EGUIA_LOWERRIGHT) + { + frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - + font->getDimension(L"A").Height - font->getKerningHeight(); + } + if (HAlign == EGUIA_LOWERRIGHT) + { + frameRect.UpperLeftCorner.X = frameRect.LowerRightCorner.X - + font->getDimension(Text.c_str()).Width; + } + + font->draw(Text.c_str(), frameRect, + OverrideColorEnabled ? OverrideColor : skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT), + HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); + } + else + { + if (font != LastBreakFont) + breakText(); + + core::rect r = frameRect; + s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); + s32 totalHeight = height * BrokenText.size(); + if (VAlign == EGUIA_CENTER) + { + r.UpperLeftCorner.Y = r.getCenter().Y - (totalHeight / 2); + } + else if (VAlign == EGUIA_LOWERRIGHT) + { + r.UpperLeftCorner.Y = r.LowerRightCorner.Y - totalHeight; + } + + irr::video::SColor previous_color(255, 255, 255, 255); + for (u32 i=0; igetDimension(BrokenText[i].c_str()).Width; + } + + std::vector colors; + std::wstring str; + + str = colorizeText(BrokenText[i].c_str(), colors, previous_color); + if (!colors.empty()) + previous_color = colors[colors.size() - 1]; + + irr::gui::CGUITTFont *tmp = static_cast(font); + tmp->draw(str.c_str(), r, + colors, + HAlign == EGUIA_CENTER, false, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); + + r.LowerRightCorner.Y += height; + r.UpperLeftCorner.Y += height; + } + } + } + } + + IGUIElement::draw(); +} + + +//! Sets another skin independent font. +void StaticText::setOverrideFont(IGUIFont* font) +{ + if (OverrideFont == font) + return; + + if (OverrideFont) + OverrideFont->drop(); + + OverrideFont = font; + + if (OverrideFont) + OverrideFont->grab(); + + breakText(); +} + +//! Gets the override font (if any) +IGUIFont * StaticText::getOverrideFont() const +{ + return OverrideFont; +} + +//! Get the font which is used right now for drawing +IGUIFont* StaticText::getActiveFont() const +{ + if ( OverrideFont ) + return OverrideFont; + IGUISkin* skin = Environment->getSkin(); + if (skin) + return skin->getFont(); + return 0; +} + +//! Sets another color for the text. +void StaticText::setOverrideColor(video::SColor color) +{ + OverrideColor = color; + OverrideColorEnabled = true; +} + + +//! Sets another color for the text. +void StaticText::setBackgroundColor(video::SColor color) +{ + BGColor = color; + OverrideBGColorEnabled = true; + Background = true; +} + + +//! Sets whether to draw the background +void StaticText::setDrawBackground(bool draw) +{ + Background = draw; +} + + +//! Gets the background color +video::SColor StaticText::getBackgroundColor() const +{ + return BGColor; +} + + +//! Checks if background drawing is enabled +bool StaticText::isDrawBackgroundEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return Background; +} + + +//! Sets whether to draw the border +void StaticText::setDrawBorder(bool draw) +{ + Border = draw; +} + + +//! Checks if border drawing is enabled +bool StaticText::isDrawBorderEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return Border; +} + + +void StaticText::setTextRestrainedInside(bool restrainTextInside) +{ + RestrainTextInside = restrainTextInside; +} + + +bool StaticText::isTextRestrainedInside() const +{ + return RestrainTextInside; +} + + +void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) +{ + HAlign = horizontal; + VAlign = vertical; +} + + +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 +const video::SColor& StaticText::getOverrideColor() const +#else +video::SColor StaticText::getOverrideColor() const +#endif +{ + return OverrideColor; +} + + +//! Sets if the static text should use the overide color or the +//! color in the gui skin. +void StaticText::enableOverrideColor(bool enable) +{ + OverrideColorEnabled = enable; +} + + +bool StaticText::isOverrideColorEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return OverrideColorEnabled; +} + + +//! Enables or disables word wrap for using the static text as +//! multiline text control. +void StaticText::setWordWrap(bool enable) +{ + WordWrap = enable; + breakText(); +} + + +bool StaticText::isWordWrapEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return WordWrap; +} + + +void StaticText::setRightToLeft(bool rtl) +{ + if (RightToLeft != rtl) + { + RightToLeft = rtl; + breakText(); + } +} + + +bool StaticText::isRightToLeft() const +{ + return RightToLeft; +} + + +//! Breaks the single text line. +void StaticText::breakText() +{ + if (!WordWrap) + return; + + BrokenText.clear(); + + IGUISkin* skin = Environment->getSkin(); + IGUIFont* font = getActiveFont(); + if (!font) + return; + + LastBreakFont = font; + + core::stringw line; + core::stringw word; + core::stringw whitespace; + s32 size = Text.size(); + s32 length = 0; + s32 elWidth = RelativeRect.getWidth(); + if (Border) + elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X); + wchar_t c; + + std::vector colors; + + // We have to deal with right-to-left and left-to-right differently + // However, most parts of the following code is the same, it's just + // some order and boundaries which change. + if (!RightToLeft) + { + // regular (left-to-right) + for (s32 i=0; igetDimension(whitespace.c_str()).Width; + const std::wstring sanitized = removeEscapes(word.c_str()); + const s32 wordlgth = font->getDimension(sanitized.c_str()).Width; + + if (wordlgth > elWidth) + { + // This word is too long to fit in the available space, look for + // the Unicode Soft HYphen (SHY / 00AD) character for a place to + // break the word at + int where = word.findFirst( wchar_t(0x00AD) ); + if (where != -1) + { + core::stringw first = word.subString(0, where); + core::stringw second = word.subString(where, word.size() - where); + BrokenText.push_back(line + first + L"-"); + const s32 secondLength = font->getDimension(second.c_str()).Width; + + length = secondLength; + line = second; + } + else + { + // No soft hyphen found, so there's nothing more we can do + // break to next line + if (length) + BrokenText.push_back(line); + length = wordlgth; + line = word; + } + } + else if (length && (length + wordlgth + whitelgth > elWidth)) + { + // break to next line + BrokenText.push_back(line); + length = wordlgth; + line = word; + } + else + { + // add word to line + line += whitespace; + line += word; + length += whitelgth + wordlgth; + } + + word = L""; + whitespace = L""; + } + + if ( isWhitespace ) + { + whitespace += c; + } + + // compute line break + if (lineBreak) + { + line += whitespace; + line += word; + BrokenText.push_back(line); + line = L""; + word = L""; + whitespace = L""; + length = 0; + } + } + } + + line += whitespace; + line += word; + BrokenText.push_back(line); + } + else + { + // right-to-left + for (s32 i=size; i>=0; --i) + { + c = Text[i]; + bool lineBreak = false; + + if (c == L'\r') // Mac or Windows breaks + { + lineBreak = true; + if ((i>0) && Text[i-1] == L'\n') // Windows breaks + { + Text.erase(i-1); + --size; + } + c = '\0'; + } + else if (c == L'\n') // Unix breaks + { + lineBreak = true; + c = '\0'; + } + + if (c==L' ' || c==0 || i==0) + { + if (word.size()) + { + // here comes the next whitespace, look if + // we must break the last word to the next line. + const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; + const s32 wordlgth = font->getDimension(word.c_str()).Width; + + if (length && (length + wordlgth + whitelgth > elWidth)) + { + // break to next line + BrokenText.push_back(line); + length = wordlgth; + line = word; + } + else + { + // add word to line + line = whitespace + line; + line = word + line; + length += whitelgth + wordlgth; + } + + word = L""; + whitespace = L""; + } + + if (c != 0) + whitespace = core::stringw(&c, 1) + whitespace; + + // compute line break + if (lineBreak) + { + line = whitespace + line; + line = word + line; + BrokenText.push_back(line); + line = L""; + word = L""; + whitespace = L""; + length = 0; + } + } + else + { + // yippee this is a word.. + word = core::stringw(&c, 1) + word; + } + } + + line = whitespace + line; + line = word + line; + BrokenText.push_back(line); + } +} + + +//! Sets the new caption of this element. +void StaticText::setText(const wchar_t* text) +{ + IGUIElement::setText(text); + breakText(); +} + + +void StaticText::updateAbsolutePosition() +{ + IGUIElement::updateAbsolutePosition(); + breakText(); +} + + +//! Returns the height of the text in pixels when it is drawn. +s32 StaticText::getTextHeight() const +{ + IGUIFont* font = getActiveFont(); + if (!font) + return 0; + + s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); + + if (WordWrap) + height *= BrokenText.size(); + + return height; +} + + +s32 StaticText::getTextWidth() const +{ + IGUIFont * font = getActiveFont(); + if(!font) + return 0; + + if(WordWrap) + { + s32 widest = 0; + + for(u32 line = 0; line < BrokenText.size(); ++line) + { + s32 width = font->getDimension(BrokenText[line].c_str()).Width; + + if(width > widest) + widest = width; + } + + return widest; + } + else + { + return font->getDimension(Text.c_str()).Width; + } +} + + +//! Writes attributes of the element. +//! Implement this to expose the attributes of your element for +//! scripting languages, editors, debuggers or xml serialization purposes. +void StaticText::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const +{ + IGUIStaticText::serializeAttributes(out,options); + + out->addBool ("Border", Border); + out->addBool ("OverrideColorEnabled",OverrideColorEnabled); + out->addBool ("OverrideBGColorEnabled",OverrideBGColorEnabled); + out->addBool ("WordWrap", WordWrap); + out->addBool ("Background", Background); + out->addBool ("RightToLeft", RightToLeft); + out->addBool ("RestrainTextInside", RestrainTextInside); + out->addColor ("OverrideColor", OverrideColor); + out->addColor ("BGColor", BGColor); + out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); + out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); + + // out->addFont ("OverrideFont", OverrideFont); +} + + +//! Reads attributes of the element +void StaticText::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) +{ + IGUIStaticText::deserializeAttributes(in,options); + + Border = in->getAttributeAsBool("Border"); + enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); + OverrideBGColorEnabled = in->getAttributeAsBool("OverrideBGColorEnabled"); + setWordWrap(in->getAttributeAsBool("WordWrap")); + Background = in->getAttributeAsBool("Background"); + RightToLeft = in->getAttributeAsBool("RightToLeft"); + RestrainTextInside = in->getAttributeAsBool("RestrainTextInside"); + OverrideColor = in->getAttributeAsColor("OverrideColor"); + BGColor = in->getAttributeAsColor("BGColor"); + + setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), + (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); + + // OverrideFont = in->getAttributeAsFont("OverrideFont"); +} + +} // end namespace gui +} // end namespace irr + + +#endif // _IRR_COMPILE_WITH_GUI_ diff --git a/src/util/statictext.h b/src/util/statictext.h new file mode 100644 index 000000000..8d2f879e7 --- /dev/null +++ b/src/util/statictext.h @@ -0,0 +1,150 @@ +// Copyright (C) 2002-2012 Nikolaus Gebhardt +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#ifndef __C_GUI_STATIC_TEXT_H_INCLUDED__ +#define __C_GUI_STATIC_TEXT_H_INCLUDED__ + +#include "IrrCompileConfig.h" +#ifdef _IRR_COMPILE_WITH_GUI_ + +#include "IGUIStaticText.h" +#include "irrArray.h" + +#include + +namespace irr +{ +namespace gui +{ + class StaticText : public IGUIStaticText + { + public: + + //! constructor + StaticText(const wchar_t* text, bool border, IGUIEnvironment* environment, + IGUIElement* parent, s32 id, const core::rect& rectangle, + bool background = false); + + //! destructor + virtual ~StaticText(); + + //! draws the element and its children + virtual void draw(); + + //! Sets another skin independent font. + virtual void setOverrideFont(IGUIFont* font=0); + + //! Gets the override font (if any) + virtual IGUIFont* getOverrideFont() const; + + //! Get the font which is used right now for drawing + virtual IGUIFont* getActiveFont() const; + + //! Sets another color for the text. + virtual void setOverrideColor(video::SColor color); + + //! Sets another color for the background. + virtual void setBackgroundColor(video::SColor color); + + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw); + + //! Gets the background color + virtual video::SColor getBackgroundColor() const; + + //! Checks if background drawing is enabled + virtual bool isDrawBackgroundEnabled() const; + + //! Sets whether to draw the border + virtual void setDrawBorder(bool draw); + + //! Checks if border drawing is enabled + virtual bool isDrawBorderEnabled() const; + + //! Sets alignment mode for text + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); + + //! Gets the override color + #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 + virtual const video::SColor& getOverrideColor() const; + #else + virtual video::SColor getOverrideColor() const; + #endif + + //! Sets if the static text should use the overide color or the + //! color in the gui skin. + virtual void enableOverrideColor(bool enable); + + //! Checks if an override color is enabled + virtual bool isOverrideColorEnabled() const; + + //! Set whether the text in this label should be clipped if it goes outside bounds + virtual void setTextRestrainedInside(bool restrainedInside); + + //! Checks if the text in this label should be clipped if it goes outside bounds + virtual bool isTextRestrainedInside() const; + + //! Enables or disables word wrap for using the static text as + //! multiline text control. + virtual void setWordWrap(bool enable); + + //! Checks if word wrap is enabled + virtual bool isWordWrapEnabled() const; + + //! Sets the new caption of this element. + virtual void setText(const wchar_t* text); + + //! Returns the height of the text in pixels when it is drawn. + virtual s32 getTextHeight() const; + + //! Returns the width of the current text, in the current font + virtual s32 getTextWidth() const; + + //! Updates the absolute position, splits text if word wrap is enabled + virtual void updateAbsolutePosition(); + + //! Set whether the string should be interpreted as right-to-left (RTL) text + /** \note This component does not implement the Unicode bidi standard, the + text of the component should be already RTL if you call this. The + main difference when RTL is enabled is that the linebreaks for multiline + elements are performed starting from the end. + */ + virtual void setRightToLeft(bool rtl); + + //! Checks if the text should be interpreted as right-to-left text + virtual bool isRightToLeft() const; + + //! Writes attributes of the element. + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; + + //! Reads attributes of the element + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); + + private: + + //! Breaks the single text line. + void breakText(); + + EGUI_ALIGNMENT HAlign, VAlign; + bool Border; + bool OverrideColorEnabled; + bool OverrideBGColorEnabled; + bool WordWrap; + bool Background; + bool RestrainTextInside; + bool RightToLeft; + + video::SColor OverrideColor, BGColor; + gui::IGUIFont* OverrideFont; + gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated. + + core::array< core::stringw > BrokenText; + }; + +} // end namespace gui +} // end namespace irr + +#endif // _IRR_COMPILE_WITH_GUI_ + +#endif // C_GUI_STATIC_TEXT_H_INCLUDED -- cgit v1.2.3 From 14ef2b445adcec770defe1abf83af9d22ccf39d8 Mon Sep 17 00:00:00 2001 From: Ekdohibs Date: Tue, 31 May 2016 17:30:11 +0200 Subject: Add colored text (not only colored chat). Add documentation, move files to a proper place and avoid memory leaks. Make it work with most kind of texts, and allow backgrounds too. --- builtin/game/chatcommands.lua | 2 +- builtin/game/misc.lua | 43 ++- builtin/settingtypes.txt | 5 + doc/lua_api.txt | 18 + src/CMakeLists.txt | 2 + src/cguittfont/CGUITTFont.cpp | 30 +- src/cguittfont/CGUITTFont.h | 7 + src/chat.cpp | 37 +- src/chat.h | 17 +- src/client/CMakeLists.txt | 1 - src/client/guiChatConsole.cpp | 664 ---------------------------------- src/client/guiChatConsole.h | 138 ------- src/defaultsettings.cpp | 2 + src/game.cpp | 53 ++- src/guiChatConsole.cpp | 664 ++++++++++++++++++++++++++++++++++ src/guiChatConsole.h | 138 +++++++ src/guiEngine.cpp | 23 +- src/guiEngine.h | 3 + src/guiFormSpecMenu.cpp | 59 +-- src/guiFormSpecMenu.h | 13 +- src/irrlicht_changes/CMakeLists.txt | 7 + src/irrlicht_changes/static_text.cpp | 679 +++++++++++++++++++++++++++++++++++ src/irrlicht_changes/static_text.h | 268 ++++++++++++++ src/terminal_chat_console.cpp | 10 +- src/util/CMakeLists.txt | 11 +- src/util/coloredstring.cpp | 68 ---- src/util/coloredstring.h | 44 --- src/util/enriched_string.cpp | 166 +++++++++ src/util/enriched_string.h | 91 +++++ src/util/statictext.cpp | 654 --------------------------------- src/util/statictext.h | 150 -------- src/util/string.h | 32 ++ 32 files changed, 2235 insertions(+), 1864 deletions(-) delete mode 100644 src/client/guiChatConsole.cpp delete mode 100644 src/client/guiChatConsole.h create mode 100644 src/guiChatConsole.cpp create mode 100644 src/guiChatConsole.h create mode 100644 src/irrlicht_changes/CMakeLists.txt create mode 100644 src/irrlicht_changes/static_text.cpp create mode 100644 src/irrlicht_changes/static_text.h delete mode 100644 src/util/coloredstring.cpp delete mode 100644 src/util/coloredstring.h create mode 100644 src/util/enriched_string.cpp create mode 100644 src/util/enriched_string.h delete mode 100644 src/util/statictext.cpp delete mode 100644 src/util/statictext.h (limited to 'src/util') diff --git a/builtin/game/chatcommands.lua b/builtin/game/chatcommands.lua index 2627559a5..22755386b 100644 --- a/builtin/game/chatcommands.lua +++ b/builtin/game/chatcommands.lua @@ -102,7 +102,7 @@ core.register_chatcommand("help", { description = "Get help for commands or list privileges", func = function(name, param) local function format_help_line(cmd, def) - local msg = core.colorize("00ffff", "/"..cmd) + local msg = core.colorize("#00ffff", "/"..cmd) if def.params and def.params ~= "" then msg = msg .. " " .. def.params end diff --git a/builtin/game/misc.lua b/builtin/game/misc.lua index 8d5c80216..918315656 100644 --- a/builtin/game/misc.lua +++ b/builtin/game/misc.lua @@ -198,19 +198,34 @@ function core.http_add_fetch(httpenv) return httpenv end -function core.get_color_escape_sequence(color) - --if string.len(color) == 3 then - -- local r = string.sub(color, 1, 1) - -- local g = string.sub(color, 2, 2) - -- local b = string.sub(color, 3, 3) - -- color = r .. r .. g .. g .. b .. b - --end - - --assert(#color == 6, "Color must be six characters in length.") - --return "\v" .. color - return "\v(color;" .. color .. ")" -end +if minetest.setting_getbool("disable_escape_sequences") then + + function core.get_color_escape_sequence(color) + return "" + end + + function core.get_background_escape_sequence(color) + return "" + end + + function core.colorize(color, message) + return message + end + +else + + local ESCAPE_CHAR = string.char(0x1b) + function core.get_color_escape_sequence(color) + return ESCAPE_CHAR .. "(c@" .. color .. ")" + end + + function core.get_background_escape_sequence(color) + return ESCAPE_CHAR .. "(b@" .. color .. ")" + end + + function core.colorize(color, message) + return core.get_color_escape_sequence(color) .. message .. core.get_color_escape_sequence("#ffffff") + end -function core.colorize(color, message) - return core.get_color_escape_sequence(color) .. message .. core.get_color_escape_sequence("ffffff") end + diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 93fb8e952..538a04f33 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -615,6 +615,11 @@ server_announce (Announce server) bool false # If you want to announce your ipv6 address, use serverlist_url = v6.servers.minetest.net. serverlist_url (Serverlist URL) string servers.minetest.net +# Disable escape sequences, e.g. chat coloring. +# Use this if you want to run a server with pre-0.4.14 clients and you want to disable +# the escape sequences generated by mods. +disable_escape_sequences (Disable escape sequences) bool false + [*Network] # Network port to listen (UDP). diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 82a0acbee..aa0d7e45d 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1701,6 +1701,24 @@ numerical form, the raw integer value of an ARGB8 quad: or string form, a ColorString (defined above): `colorspec = "green"` +Escape sequences +---------------- +Most text can contain escape sequences, that can for example color the text. +There are a few exceptions: tab headers, dropdowns and vertical labels can't. +The following functions provide escape sequences: +* `core.get_color_escape_sequence(color)`: + * `color` is a ColorString + * The escape sequence sets the text color to `color` +* `core.colorize(color, message)`: + * Equivalent to: + `core.get_color_escape_sequence(color) .. + message .. + core.get_color_escape_sequence("#ffffff")` +* `color.get_background_escape_sequence(color)` + * `color` is a ColorString + * The escape sequence sets the background of the whole text element to + `color`. Only defined for item descriptions and tooltips. + Spatial Vectors --------------- * `vector.new(a[, b, c])`: returns a vector: diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ea1564eeb..f02812415 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -376,6 +376,7 @@ add_subdirectory(network) add_subdirectory(script) add_subdirectory(unittest) add_subdirectory(util) +add_subdirectory(irrlicht_changes) set(common_SRCS ban.cpp @@ -493,6 +494,7 @@ set(client_SRCS ${common_SRCS} ${sound_SRCS} ${client_network_SRCS} + ${client_irrlicht_changes_SRCS} camera.cpp client.cpp clientmap.cpp diff --git a/src/cguittfont/CGUITTFont.cpp b/src/cguittfont/CGUITTFont.cpp index 2342eb748..c2d37c6c0 100644 --- a/src/cguittfont/CGUITTFont.cpp +++ b/src/cguittfont/CGUITTFont.cpp @@ -1,6 +1,7 @@ /* CGUITTFont FreeType class for Irrlicht Copyright (c) 2009-2010 John Norman + Copyright (c) 2016 Nathanaël Courant This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any @@ -545,6 +546,13 @@ void CGUITTFont::setFontHinting(const bool enable, const bool enable_auto_hintin void CGUITTFont::draw(const core::stringw& text, const core::rect& position, video::SColor color, bool hcenter, bool vcenter, const core::rect* clip) { + draw(EnrichedString(std::wstring(text.c_str()), color), position, color, hcenter, vcenter, clip); +} + +void CGUITTFont::draw(const EnrichedString &text, const core::rect& position, video::SColor color, bool hcenter, bool vcenter, const core::rect* clip) +{ + std::vector colors = text.getColors(); + if (!Driver) return; @@ -572,7 +580,7 @@ void CGUITTFont::draw(const core::stringw& text, const core::rect& position } // Convert to a unicode string. - core::ustring utext(text); + core::ustring utext = text.getString(); // Set up our render map. core::map Render_Map; @@ -581,6 +589,7 @@ void CGUITTFont::draw(const core::stringw& text, const core::rect& position u32 n; uchar32_t previousChar = 0; core::ustring::const_iterator iter(utext); + std::vector applied_colors; while (!iter.atEnd()) { uchar32_t currentChar = *iter; @@ -590,7 +599,7 @@ void CGUITTFont::draw(const core::stringw& text, const core::rect& position if (currentChar == L'\r') // Mac or Windows breaks { lineBreak = true; - if (*(iter + 1) == (uchar32_t)'\n') // Windows line breaks. + if (*(iter + 1) == (uchar32_t)'\n') // Windows line breaks. currentChar = *(++iter); } else if (currentChar == (uchar32_t)'\n') // Unix breaks @@ -627,6 +636,9 @@ void CGUITTFont::draw(const core::stringw& text, const core::rect& position page->render_positions.push_back(core::position2di(offset.X + offx, offset.Y + offy)); page->render_source_rects.push_back(glyph.source_rect); Render_Map.set(glyph.glyph_page, page); + u32 current_color = iter.getPos(); + if (current_color < colors.size()) + applied_colors.push_back(colors[current_color]); } offset.X += getWidthFromCharacter(currentChar); @@ -645,8 +657,6 @@ void CGUITTFont::draw(const core::stringw& text, const core::rect& position CGUITTGlyphPage* page = n->getValue(); - if (!use_transparency) color.color |= 0xff000000; - if (shadow_offset) { for (size_t i = 0; i < page->render_positions.size(); ++i) page->render_positions[i] += core::vector2di(shadow_offset, shadow_offset); @@ -654,7 +664,17 @@ void CGUITTFont::draw(const core::stringw& text, const core::rect& position for (size_t i = 0; i < page->render_positions.size(); ++i) page->render_positions[i] -= core::vector2di(shadow_offset, shadow_offset); } - Driver->draw2DImageBatch(page->texture, page->render_positions, page->render_source_rects, clip, color, true); + for (size_t i = 0; i < page->render_positions.size(); ++i) { + irr::video::SColor col; + if (!applied_colors.empty()) { + col = applied_colors[i < applied_colors.size() ? i : 0]; + } else { + col = irr::video::SColor(255, 255, 255, 255); + } + if (!use_transparency) + col.color |= 0xff000000; + Driver->draw2DImage(page->texture, page->render_positions[i], page->render_source_rects[i], clip, col, true); + } } } diff --git a/src/cguittfont/CGUITTFont.h b/src/cguittfont/CGUITTFont.h index e24d8f18b..0aa540c5c 100644 --- a/src/cguittfont/CGUITTFont.h +++ b/src/cguittfont/CGUITTFont.h @@ -1,6 +1,7 @@ /* CGUITTFont FreeType class for Irrlicht Copyright (c) 2009-2010 John Norman + Copyright (c) 2016 Nathanaël Courant This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any @@ -33,6 +34,8 @@ #include #include +#include +#include "util/enriched_string.h" #include FT_FREETYPE_H namespace irr @@ -258,6 +261,10 @@ namespace gui virtual void draw(const core::stringw& text, const core::rect& position, video::SColor color, bool hcenter=false, bool vcenter=false, const core::rect* clip=0); + + virtual void draw(const EnrichedString& text, const core::rect& position, + video::SColor color, bool hcenter=false, bool vcenter=false, + const core::rect* clip=0); //! Returns the dimension of a character produced by this font. virtual core::dimension2d getCharDimension(const wchar_t ch) const; diff --git a/src/chat.cpp b/src/chat.cpp index 958389df5..46555b3dc 100644 --- a/src/chat.cpp +++ b/src/chat.cpp @@ -267,28 +267,26 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, next_frags.push_back(temp_frag); } - std::wstring name_sanitized = removeEscapes(line.name); + std::wstring name_sanitized = line.name.c_str(); // Choose an indentation level if (line.name.empty()) { // Server messages hanging_indentation = 0; - } - else if (name_sanitized.size() + 3 <= cols/2) { + } else if (name_sanitized.size() + 3 <= cols/2) { // Names shorter than about half the console width hanging_indentation = line.name.size() + 3; - } - else { + } else { // Very long names hanging_indentation = 2; } - ColoredString line_text(line.text); + //EnrichedString line_text(line.text); next_line.first = true; bool text_processing = false; // Produce fragments and layout them into lines - while (!next_frags.empty() || in_pos < line_text.size()) + while (!next_frags.empty() || in_pos < line.text.size()) { // Layout fragments into lines while (!next_frags.empty()) @@ -326,9 +324,9 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, } // Produce fragment - if (in_pos < line_text.size()) + if (in_pos < line.text.size()) { - u32 remaining_in_input = line_text.size() - in_pos; + u32 remaining_in_input = line.text.size() - in_pos; u32 remaining_in_output = cols - out_column; // Determine a fragment length <= the minimum of @@ -338,14 +336,14 @@ u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, while (frag_length < remaining_in_input && frag_length < remaining_in_output) { - if (isspace(line_text[in_pos + frag_length])) + if (isspace(line.text.getString()[in_pos + frag_length])) space_pos = frag_length; ++frag_length; } if (space_pos != 0 && frag_length < remaining_in_input) frag_length = space_pos + 1; - temp_frag.text = line_text.substr(in_pos, frag_length); + temp_frag.text = line.text.substr(in_pos, frag_length); temp_frag.column = 0; //temp_frag.bold = 0; next_frags.push_back(temp_frag); @@ -729,19 +727,22 @@ ChatBuffer& ChatBackend::getRecentBuffer() return m_recent_buffer; } -std::wstring ChatBackend::getRecentChat() +EnrichedString ChatBackend::getRecentChat() { - std::wostringstream stream; + EnrichedString result; for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i) { const ChatLine& line = m_recent_buffer.getLine(i); if (i != 0) - stream << L"\n"; - if (!line.name.empty()) - stream << L"<" << line.name << L"> "; - stream << line.text; + result += L"\n"; + if (!line.name.empty()) { + result += L"<"; + result += line.name; + result += L"> "; + } + result += line.text; } - return stream.str(); + return result; } ChatPrompt& ChatBackend::getPrompt() diff --git a/src/chat.h b/src/chat.h index 661cafc82..11061fd39 100644 --- a/src/chat.h +++ b/src/chat.h @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "irrlichttypes.h" -#include "util/coloredstring.h" +#include "util/enriched_string.h" // Chat console related classes @@ -34,9 +34,9 @@ struct ChatLine // age in seconds f32 age; // name of sending player, or empty if sent by server - std::wstring name; + EnrichedString name; // message text - ColoredString text; + EnrichedString text; ChatLine(std::wstring a_name, std::wstring a_text): age(0.0), @@ -44,12 +44,19 @@ struct ChatLine text(a_text) { } + + ChatLine(EnrichedString a_name, EnrichedString a_text): + age(0.0), + name(a_name), + text(a_text) + { + } }; struct ChatFormattedFragment { // text string - std::wstring text; + EnrichedString text; // starting column u32 column; // formatting @@ -262,7 +269,7 @@ public: // Get the recent messages buffer ChatBuffer& getRecentBuffer(); // Concatenate all recent messages - std::wstring getRecentChat(); + EnrichedString getRecentChat(); // Get the console prompt ChatPrompt& getPrompt(); diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index bcf114760..a1ec37fe3 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -1,6 +1,5 @@ set(client_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/clientlauncher.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/guiChatConsole.cpp ${CMAKE_CURRENT_SOURCE_DIR}/tile.cpp PARENT_SCOPE ) diff --git a/src/client/guiChatConsole.cpp b/src/client/guiChatConsole.cpp deleted file mode 100644 index d8837556a..000000000 --- a/src/client/guiChatConsole.cpp +++ /dev/null @@ -1,664 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#include "guiChatConsole.h" -#include "chat.h" -#include "client.h" -#include "debug.h" -#include "gettime.h" -#include "keycode.h" -#include "settings.h" -#include "porting.h" -#include "client/tile.h" -#include "fontengine.h" -#include "log.h" -#include "gettext.h" -#include - -#if USE_FREETYPE - #include "xCGUITTFont.h" -#endif - -inline u32 clamp_u8(s32 value) -{ - return (u32) MYMIN(MYMAX(value, 0), 255); -} - - -GUIChatConsole::GUIChatConsole( - gui::IGUIEnvironment* env, - gui::IGUIElement* parent, - s32 id, - ChatBackend* backend, - Client* client, - IMenuManager* menumgr -): - IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, - core::rect(0,0,100,100)), - m_chat_backend(backend), - m_client(client), - m_menumgr(menumgr), - m_screensize(v2u32(0,0)), - m_animate_time_old(0), - m_open(false), - m_close_on_enter(false), - m_height(0), - m_desired_height(0), - m_desired_height_fraction(0.0), - m_height_speed(5.0), - m_open_inhibited(0), - m_cursor_blink(0.0), - m_cursor_blink_speed(0.0), - m_cursor_height(0.0), - m_background(NULL), - m_background_color(255, 0, 0, 0), - m_font(NULL), - m_fontsize(0, 0) -{ - m_animate_time_old = getTimeMs(); - - // load background settings - s32 console_alpha = g_settings->getS32("console_alpha"); - m_background_color.setAlpha(clamp_u8(console_alpha)); - - // load the background texture depending on settings - ITextureSource *tsrc = client->getTextureSource(); - if (tsrc->isKnownSourceImage("background_chat.jpg")) { - m_background = tsrc->getTexture("background_chat.jpg"); - m_background_color.setRed(255); - m_background_color.setGreen(255); - m_background_color.setBlue(255); - } else { - v3f console_color = g_settings->getV3F("console_color"); - m_background_color.setRed(clamp_u8(myround(console_color.X))); - m_background_color.setGreen(clamp_u8(myround(console_color.Y))); - m_background_color.setBlue(clamp_u8(myround(console_color.Z))); - } - - m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); - - if (m_font == NULL) - { - errorstream << "GUIChatConsole: Unable to load mono font "; - } - else - { - core::dimension2d dim = m_font->getDimension(L"M"); - m_fontsize = v2u32(dim.Width, dim.Height); - m_font->grab(); - } - m_fontsize.X = MYMAX(m_fontsize.X, 1); - m_fontsize.Y = MYMAX(m_fontsize.Y, 1); - - // set default cursor options - setCursor(true, true, 2.0, 0.1); -} - -GUIChatConsole::~GUIChatConsole() -{ - if (m_font) - m_font->drop(); -} - -void GUIChatConsole::openConsole(f32 height) -{ - m_open = true; - m_desired_height_fraction = height; - m_desired_height = height * m_screensize.Y; - reformatConsole(); - m_animate_time_old = getTimeMs(); - IGUIElement::setVisible(true); - Environment->setFocus(this); - m_menumgr->createdMenu(this); -} - -bool GUIChatConsole::isOpen() const -{ - return m_open; -} - -bool GUIChatConsole::isOpenInhibited() const -{ - return m_open_inhibited > 0; -} - -void GUIChatConsole::closeConsole() -{ - m_open = false; - Environment->removeFocus(this); - m_menumgr->deletingMenu(this); -} - -void GUIChatConsole::closeConsoleAtOnce() -{ - closeConsole(); - m_height = 0; - recalculateConsolePosition(); -} - -f32 GUIChatConsole::getDesiredHeight() const -{ - return m_desired_height_fraction; -} - -void GUIChatConsole::replaceAndAddToHistory(std::wstring line) -{ - ChatPrompt& prompt = m_chat_backend->getPrompt(); - prompt.addToHistory(prompt.getLine()); - prompt.replace(line); -} - - -void GUIChatConsole::setCursor( - bool visible, bool blinking, f32 blink_speed, f32 relative_height) -{ - if (visible) - { - if (blinking) - { - // leave m_cursor_blink unchanged - m_cursor_blink_speed = blink_speed; - } - else - { - m_cursor_blink = 0x8000; // on - m_cursor_blink_speed = 0.0; - } - } - else - { - m_cursor_blink = 0; // off - m_cursor_blink_speed = 0.0; - } - m_cursor_height = relative_height; -} - -void GUIChatConsole::draw() -{ - if(!IsVisible) - return; - - video::IVideoDriver* driver = Environment->getVideoDriver(); - - // Check screen size - v2u32 screensize = driver->getScreenSize(); - if (screensize != m_screensize) - { - // screen size has changed - // scale current console height to new window size - if (m_screensize.Y != 0) - m_height = m_height * screensize.Y / m_screensize.Y; - m_desired_height = m_desired_height_fraction * m_screensize.Y; - m_screensize = screensize; - reformatConsole(); - } - - // Animation - u32 now = getTimeMs(); - animate(now - m_animate_time_old); - m_animate_time_old = now; - - // Draw console elements if visible - if (m_height > 0) - { - drawBackground(); - drawText(); - drawPrompt(); - } - - gui::IGUIElement::draw(); -} - -void GUIChatConsole::reformatConsole() -{ - s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) - s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt - if (cols <= 0 || rows <= 0) - cols = rows = 0; - m_chat_backend->reformat(cols, rows); -} - -void GUIChatConsole::recalculateConsolePosition() -{ - core::rect rect(0, 0, m_screensize.X, m_height); - DesiredRect = rect; - recalculateAbsolutePosition(false); -} - -void GUIChatConsole::animate(u32 msec) -{ - // animate the console height - s32 goal = m_open ? m_desired_height : 0; - - // Set invisible if close animation finished (reset by openConsole) - // This function (animate()) is never called once its visibility becomes false so do not - // actually set visible to false before the inhibited period is over - if (!m_open && m_height == 0 && m_open_inhibited == 0) - IGUIElement::setVisible(false); - - if (m_height != goal) - { - s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); - if (max_change == 0) - max_change = 1; - - if (m_height < goal) - { - // increase height - if (m_height + max_change < goal) - m_height += max_change; - else - m_height = goal; - } - else - { - // decrease height - if (m_height > goal + max_change) - m_height -= max_change; - else - m_height = goal; - } - - recalculateConsolePosition(); - } - - // blink the cursor - if (m_cursor_blink_speed != 0.0) - { - u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); - if (blink_increase == 0) - blink_increase = 1; - m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff); - } - - // decrease open inhibit counter - if (m_open_inhibited > msec) - m_open_inhibited -= msec; - else - m_open_inhibited = 0; -} - -void GUIChatConsole::drawBackground() -{ - video::IVideoDriver* driver = Environment->getVideoDriver(); - if (m_background != NULL) - { - core::rect sourcerect(0, -m_height, m_screensize.X, 0); - driver->draw2DImage( - m_background, - v2s32(0, 0), - sourcerect, - &AbsoluteClippingRect, - m_background_color, - false); - } - else - { - driver->draw2DRectangle( - m_background_color, - core::rect(0, 0, m_screensize.X, m_height), - &AbsoluteClippingRect); - } -} - -void GUIChatConsole::drawText() -{ - if (m_font == NULL) - return; - - ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); - for (u32 row = 0; row < buf.getRows(); ++row) - { - const ChatFormattedLine& line = buf.getFormattedLine(row); - if (line.fragments.empty()) - continue; - - s32 line_height = m_fontsize.Y; - s32 y = row * line_height + m_height - m_desired_height; - if (y + line_height < 0) - continue; - - for (u32 i = 0; i < line.fragments.size(); ++i) - { - const ChatFormattedFragment& fragment = line.fragments[i]; - s32 x = (fragment.column + 1) * m_fontsize.X; - core::rect destrect( - x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); - - - #if USE_FREETYPE - // Draw colored text if FreeType is enabled - irr::gui::CGUITTFont *tmp = static_cast(m_font); - tmp->draw( - fragment.text.c_str(), - destrect, - fragment.text.getColors(), - false, - false, - &AbsoluteClippingRect); - #else - // Otherwise use standard text - m_font->draw( - fragment.text.c_str(), - destrect, - video::SColor(255, 255, 255, 255), - false, - false, - &AbsoluteClippingRect); - #endif - } - } -} - -void GUIChatConsole::drawPrompt() -{ - if (m_font == NULL) - return; - - u32 row = m_chat_backend->getConsoleBuffer().getRows(); - s32 line_height = m_fontsize.Y; - s32 y = row * line_height + m_height - m_desired_height; - - ChatPrompt& prompt = m_chat_backend->getPrompt(); - std::wstring prompt_text = prompt.getVisiblePortion(); - - // FIXME Draw string at once, not character by character - // That will only work with the cursor once we have a monospace font - for (u32 i = 0; i < prompt_text.size(); ++i) - { - wchar_t ws[2] = {prompt_text[i], 0}; - s32 x = (1 + i) * m_fontsize.X; - core::rect destrect( - x, y, x + m_fontsize.X, y + m_fontsize.Y); - m_font->draw( - ws, - destrect, - video::SColor(255, 255, 255, 255), - false, - false, - &AbsoluteClippingRect); - } - - // Draw the cursor during on periods - if ((m_cursor_blink & 0x8000) != 0) - { - s32 cursor_pos = prompt.getVisibleCursorPosition(); - if (cursor_pos >= 0) - { - s32 cursor_len = prompt.getCursorLength(); - video::IVideoDriver* driver = Environment->getVideoDriver(); - s32 x = (1 + cursor_pos) * m_fontsize.X; - core::rect destrect( - x, - y + m_fontsize.Y * (1.0 - m_cursor_height), - x + m_fontsize.X * MYMAX(cursor_len, 1), - y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) - ); - video::SColor cursor_color(255,255,255,255); - driver->draw2DRectangle( - cursor_color, - destrect, - &AbsoluteClippingRect); - } - } - -} - -bool GUIChatConsole::OnEvent(const SEvent& event) -{ - - ChatPrompt &prompt = m_chat_backend->getPrompt(); - - if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) - { - // Key input - if(KeyPress(event.KeyInput) == getKeySetting("keymap_console")) - { - closeConsole(); - - // inhibit open so the_game doesn't reopen immediately - m_open_inhibited = 50; - m_close_on_enter = false; - return true; - } - else if(event.KeyInput.Key == KEY_ESCAPE) - { - closeConsoleAtOnce(); - m_close_on_enter = false; - // inhibit open so the_game doesn't reopen immediately - m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" - return true; - } - else if(event.KeyInput.Key == KEY_PRIOR) - { - m_chat_backend->scrollPageUp(); - return true; - } - else if(event.KeyInput.Key == KEY_NEXT) - { - m_chat_backend->scrollPageDown(); - return true; - } - else if(event.KeyInput.Key == KEY_RETURN) - { - prompt.addToHistory(prompt.getLine()); - std::wstring text = prompt.replace(L""); - m_client->typeChatMessage(text); - if (m_close_on_enter) { - closeConsoleAtOnce(); - m_close_on_enter = false; - } - return true; - } - else if(event.KeyInput.Key == KEY_UP) - { - // Up pressed - // Move back in history - prompt.historyPrev(); - return true; - } - else if(event.KeyInput.Key == KEY_DOWN) - { - // Down pressed - // Move forward in history - prompt.historyNext(); - return true; - } - else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) - { - // Left/right pressed - // Move/select character/word to the left depending on control and shift keys - ChatPrompt::CursorOp op = event.KeyInput.Shift ? - ChatPrompt::CURSOROP_SELECT : - ChatPrompt::CURSOROP_MOVE; - ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? - ChatPrompt::CURSOROP_DIR_LEFT : - ChatPrompt::CURSOROP_DIR_RIGHT; - ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? - ChatPrompt::CURSOROP_SCOPE_WORD : - ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation(op, dir, scope); - return true; - } - else if(event.KeyInput.Key == KEY_HOME) - { - // Home pressed - // move to beginning of line - prompt.cursorOperation( - ChatPrompt::CURSOROP_MOVE, - ChatPrompt::CURSOROP_DIR_LEFT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_END) - { - // End pressed - // move to end of line - prompt.cursorOperation( - ChatPrompt::CURSOROP_MOVE, - ChatPrompt::CURSOROP_DIR_RIGHT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_BACK) - { - // Backspace or Ctrl-Backspace pressed - // delete character / word to the left - ChatPrompt::CursorOpScope scope = - event.KeyInput.Control ? - ChatPrompt::CURSOROP_SCOPE_WORD : - ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, - scope); - return true; - } - else if(event.KeyInput.Key == KEY_DELETE) - { - // Delete or Ctrl-Delete pressed - // delete character / word to the right - ChatPrompt::CursorOpScope scope = - event.KeyInput.Control ? - ChatPrompt::CURSOROP_SCOPE_WORD : - ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_RIGHT, - scope); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) - { - // Ctrl-A pressed - // Select all text - prompt.cursorOperation( - ChatPrompt::CURSOROP_SELECT, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) - { - // Ctrl-C pressed - // Copy text to clipboard - if (prompt.getCursorLength() <= 0) - return true; - std::wstring wselected = prompt.getSelection(); - std::string selected(wselected.begin(), wselected.end()); - Environment->getOSOperator()->copyToClipboard(selected.c_str()); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) - { - // Ctrl-V pressed - // paste text from clipboard - if (prompt.getCursorLength() > 0) { - // Delete selected section of text - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_SELECTION); - } - IOSOperator *os_operator = Environment->getOSOperator(); - const c8 *text = os_operator->getTextFromClipboard(); - if (!text) - return true; - std::basic_string str((const unsigned char*)text); - prompt.input(std::wstring(str.begin(), str.end())); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) - { - // Ctrl-X pressed - // Cut text to clipboard - if (prompt.getCursorLength() <= 0) - return true; - std::wstring wselected = prompt.getSelection(); - std::string selected(wselected.begin(), wselected.end()); - Environment->getOSOperator()->copyToClipboard(selected.c_str()); - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_SELECTION); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) - { - // Ctrl-U pressed - // kill line to left end - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) - { - // Ctrl-K pressed - // kill line to right end - prompt.cursorOperation( - ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_RIGHT, - ChatPrompt::CURSOROP_SCOPE_LINE); - return true; - } - else if(event.KeyInput.Key == KEY_TAB) - { - // Tab or Shift-Tab pressed - // Nick completion - std::list names = m_client->getConnectedPlayerNames(); - bool backwards = event.KeyInput.Shift; - prompt.nickCompletion(names, backwards); - return true; - } - else if(event.KeyInput.Char != 0 && !event.KeyInput.Control) - { - #if (defined(linux) || defined(__linux)) - wchar_t wc = L'_'; - mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); - prompt.input(wc); - #else - prompt.input(event.KeyInput.Char); - #endif - return true; - } - } - else if(event.EventType == EET_MOUSE_INPUT_EVENT) - { - if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) - { - s32 rows = myround(-3.0 * event.MouseInput.Wheel); - m_chat_backend->scroll(rows); - } - } - - return Parent ? Parent->OnEvent(event) : false; -} - -void GUIChatConsole::setVisible(bool visible) -{ - m_open = visible; - IGUIElement::setVisible(visible); - if (!visible) { - m_height = 0; - recalculateConsolePosition(); - } -} - diff --git a/src/client/guiChatConsole.h b/src/client/guiChatConsole.h deleted file mode 100644 index 3013a1d31..000000000 --- a/src/client/guiChatConsole.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#ifndef GUICHATCONSOLE_HEADER -#define GUICHATCONSOLE_HEADER - -#include "irrlichttypes_extrabloated.h" -#include "modalMenu.h" -#include "chat.h" -#include "config.h" - -class Client; - -class GUIChatConsole : public gui::IGUIElement -{ -public: - GUIChatConsole(gui::IGUIEnvironment* env, - gui::IGUIElement* parent, - s32 id, - ChatBackend* backend, - Client* client, - IMenuManager* menumgr); - virtual ~GUIChatConsole(); - - // Open the console (height = desired fraction of screen size) - // This doesn't open immediately but initiates an animation. - // You should call isOpenInhibited() before this. - void openConsole(f32 height); - - bool isOpen() const; - - // Check if the console should not be opened at the moment - // This is to avoid reopening the console immediately after closing - bool isOpenInhibited() const; - // Close the console, equivalent to openConsole(0). - // This doesn't close immediately but initiates an animation. - void closeConsole(); - // Close the console immediately, without animation. - void closeConsoleAtOnce(); - // Set whether to close the console after the user presses enter. - void setCloseOnEnter(bool close) { m_close_on_enter = close; } - - // Return the desired height (fraction of screen size) - // Zero if the console is closed or getting closed - f32 getDesiredHeight() const; - - // Replace actual line when adding the actual to the history (if there is any) - void replaceAndAddToHistory(std::wstring line); - - // Change how the cursor looks - void setCursor( - bool visible, - bool blinking = false, - f32 blink_speed = 1.0, - f32 relative_height = 1.0); - - // Irrlicht draw method - virtual void draw(); - - bool canTakeFocus(gui::IGUIElement* element) { return false; } - - virtual bool OnEvent(const SEvent& event); - - virtual void setVisible(bool visible); - -private: - void reformatConsole(); - void recalculateConsolePosition(); - - // These methods are called by draw - void animate(u32 msec); - void drawBackground(); - void drawText(); - void drawPrompt(); - -private: - ChatBackend* m_chat_backend; - Client* m_client; - IMenuManager* m_menumgr; - - // current screen size - v2u32 m_screensize; - - // used to compute how much time passed since last animate() - u32 m_animate_time_old; - - // should the console be opened or closed? - bool m_open; - // should it close after you press enter? - bool m_close_on_enter; - // current console height [pixels] - s32 m_height; - // desired height [pixels] - f32 m_desired_height; - // desired height [screen height fraction] - f32 m_desired_height_fraction; - // console open/close animation speed [screen height fraction / second] - f32 m_height_speed; - // if nonzero, opening the console is inhibited [milliseconds] - u32 m_open_inhibited; - - // cursor blink frame (16-bit value) - // cursor is off during [0,32767] and on during [32768,65535] - u32 m_cursor_blink; - // cursor blink speed [on/off toggles / second] - f32 m_cursor_blink_speed; - // cursor height [line height] - f32 m_cursor_height; - - // background texture - video::ITexture* m_background; - // background color (including alpha) - video::SColor m_background_color; - - // font - gui::IGUIFont* m_font; - v2u32 m_fontsize; -}; - - -#endif - diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index e8b652c17..632ec0df9 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -202,6 +202,8 @@ void set_default_settings(Settings *settings) settings->setDefault("server_name", ""); settings->setDefault("server_description", ""); + settings->setDefault("disable_escape_sequences", "false"); + #if USE_FREETYPE settings->setDefault("freetype", "true"); settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "liberationsans.ttf")); diff --git a/src/game.cpp b/src/game.cpp index 71a04aef5..def202fe5 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -34,7 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "filesys.h" #include "gettext.h" -#include "client/guiChatConsole.h" +#include "guiChatConsole.h" #include "guiFormSpecMenu.h" #include "guiKeyChangeMenu.h" #include "guiPasswordChange.h" @@ -55,14 +55,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "tool.h" #include "util/directiontables.h" #include "util/pointedthing.h" +#include "irrlicht_changes/static_text.h" #include "version.h" #include "minimap.h" #include "mapblock_mesh.h" -#if USE_FREETYPE - #include "util/statictext.h" -#endif - #include "sound.h" #if USE_SOUND @@ -541,7 +538,7 @@ void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe, std::ostringstream os(std::ios_base::binary); g_profiler->printPage(os, show_profiler, show_profiler_max); std::wstring text = utf8_to_wide(os.str()); - guitext_profiler->setText(text.c_str()); + setStaticText(guitext_profiler, text.c_str()); guitext_profiler->setVisible(true); s32 w = fe->getTextWidth(text.c_str()); @@ -1244,7 +1241,11 @@ static void updateChat(Client &client, f32 dtime, bool show_debug, // Get new messages from error log buffer while (!chat_log_error_buf.empty()) { - chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get())); + std::wstring error_message = utf8_to_wide(chat_log_error_buf.get()); + if (!g_settings->getBool("disable_escape_sequences")) { + error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)"; + } + chat_backend.addMessage(L"", error_message); } // Get new messages from client @@ -1259,10 +1260,10 @@ static void updateChat(Client &client, f32 dtime, bool show_debug, // Display all messages in a static text element unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount(); - std::wstring recent_chat = chat_backend.getRecentChat(); + EnrichedString recent_chat = chat_backend.getRecentChat(); unsigned int line_height = g_fontengine->getLineHeight(); - guitext_chat->setText(recent_chat.c_str()); + setStaticText(guitext_chat, recent_chat); // Update gui element size and position s32 chat_y = 5 + line_height; @@ -1271,7 +1272,7 @@ static void updateChat(Client &client, f32 dtime, bool show_debug, chat_y += line_height; // first pass to calculate height of text to be set - s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10, + s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10, porting::getWindowSize().X - 20); core::rect rect(10, chat_y, width, chat_y + porting::getWindowSize().Y); guitext_chat->setRelativePosition(rect); @@ -2218,45 +2219,39 @@ bool Game::createClient(const std::string &playername, bool Game::initGui() { // First line of debug text - guitext = guienv->addStaticText( + guitext = addStaticText(guienv, utf8_to_wide(PROJECT_NAME_C).c_str(), core::rect(0, 0, 0, 0), false, false, guiroot); // Second line of debug text - guitext2 = guienv->addStaticText( + guitext2 = addStaticText(guienv, L"", core::rect(0, 0, 0, 0), false, false, guiroot); // At the middle of the screen // Object infos are shown in this - guitext_info = guienv->addStaticText( + guitext_info = addStaticText(guienv, L"", core::rect(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200), false, true, guiroot); // Status text (displays info when showing and hiding GUI stuff, etc.) - guitext_status = guienv->addStaticText( + guitext_status = addStaticText(guienv, L"", core::rect(0, 0, 0, 0), false, false, guiroot); guitext_status->setVisible(false); -#if USE_FREETYPE - // Colored chat support when using FreeType - guitext_chat = new gui::StaticText(L"", false, guienv, guiroot, -1, core::rect(0, 0, 0, 0), false); - guitext_chat->setWordWrap(true); - guitext_chat->drop(); -#else - // Standard chat when FreeType is disabled // Chat text - guitext_chat = guienv->addStaticText( + guitext_chat = addStaticText( + guienv, L"", core::rect(0, 0, 0, 0), //false, false); // Disable word wrap as of now false, true, guiroot); -#endif + // Remove stale "recent" chat messages from previous connections chat_backend->clearRecentChat(); @@ -2270,7 +2265,7 @@ bool Game::initGui() } // Profiler text (size is updated when text is updated) - guitext_profiler = guienv->addStaticText( + guitext_profiler = addStaticText(guienv, L"", core::rect(0, 0, 0, 0), false, false, guiroot); @@ -4308,12 +4303,12 @@ void Game::updateGui(float *statustext_time, const RunStats &stats, << ", v_range = " << draw_control->wanted_range << std::setprecision(3) << ", RTT = " << client->getRTT(); - guitext->setText(utf8_to_wide(os.str()).c_str()); + setStaticText(guitext, utf8_to_wide(os.str()).c_str()); guitext->setVisible(true); } else if (flags.show_hud || flags.show_chat) { std::ostringstream os(std::ios_base::binary); os << PROJECT_NAME_C " " << g_version_hash; - guitext->setText(utf8_to_wide(os.str()).c_str()); + setStaticText(guitext, utf8_to_wide(os.str()).c_str()); guitext->setVisible(true); } else { guitext->setVisible(false); @@ -4350,7 +4345,7 @@ void Game::updateGui(float *statustext_time, const RunStats &stats, } } - guitext2->setText(utf8_to_wide(os.str()).c_str()); + setStaticText(guitext2, utf8_to_wide(os.str()).c_str()); guitext2->setVisible(true); core::rect rect( @@ -4362,7 +4357,7 @@ void Game::updateGui(float *statustext_time, const RunStats &stats, guitext2->setVisible(false); } - guitext_info->setText(infotext.c_str()); + setStaticText(guitext_info, infotext.c_str()); guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0); float statustext_time_max = 1.5; @@ -4376,7 +4371,7 @@ void Game::updateGui(float *statustext_time, const RunStats &stats, } } - guitext_status->setText(statustext.c_str()); + setStaticText(guitext_status, statustext.c_str()); guitext_status->setVisible(!statustext.empty()); if (!statustext.empty()) { diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp new file mode 100644 index 000000000..bb58d1305 --- /dev/null +++ b/src/guiChatConsole.cpp @@ -0,0 +1,664 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiChatConsole.h" +#include "chat.h" +#include "client.h" +#include "debug.h" +#include "gettime.h" +#include "keycode.h" +#include "settings.h" +#include "porting.h" +#include "client/tile.h" +#include "fontengine.h" +#include "log.h" +#include "gettext.h" +#include + +#if USE_FREETYPE + #include "xCGUITTFont.h" +#endif + +inline u32 clamp_u8(s32 value) +{ + return (u32) MYMIN(MYMAX(value, 0), 255); +} + + +GUIChatConsole::GUIChatConsole( + gui::IGUIEnvironment* env, + gui::IGUIElement* parent, + s32 id, + ChatBackend* backend, + Client* client, + IMenuManager* menumgr +): + IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, + core::rect(0,0,100,100)), + m_chat_backend(backend), + m_client(client), + m_menumgr(menumgr), + m_screensize(v2u32(0,0)), + m_animate_time_old(0), + m_open(false), + m_close_on_enter(false), + m_height(0), + m_desired_height(0), + m_desired_height_fraction(0.0), + m_height_speed(5.0), + m_open_inhibited(0), + m_cursor_blink(0.0), + m_cursor_blink_speed(0.0), + m_cursor_height(0.0), + m_background(NULL), + m_background_color(255, 0, 0, 0), + m_font(NULL), + m_fontsize(0, 0) +{ + m_animate_time_old = getTimeMs(); + + // load background settings + s32 console_alpha = g_settings->getS32("console_alpha"); + m_background_color.setAlpha(clamp_u8(console_alpha)); + + // load the background texture depending on settings + ITextureSource *tsrc = client->getTextureSource(); + if (tsrc->isKnownSourceImage("background_chat.jpg")) { + m_background = tsrc->getTexture("background_chat.jpg"); + m_background_color.setRed(255); + m_background_color.setGreen(255); + m_background_color.setBlue(255); + } else { + v3f console_color = g_settings->getV3F("console_color"); + m_background_color.setRed(clamp_u8(myround(console_color.X))); + m_background_color.setGreen(clamp_u8(myround(console_color.Y))); + m_background_color.setBlue(clamp_u8(myround(console_color.Z))); + } + + m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); + + if (m_font == NULL) + { + errorstream << "GUIChatConsole: Unable to load mono font "; + } + else + { + core::dimension2d dim = m_font->getDimension(L"M"); + m_fontsize = v2u32(dim.Width, dim.Height); + m_font->grab(); + } + m_fontsize.X = MYMAX(m_fontsize.X, 1); + m_fontsize.Y = MYMAX(m_fontsize.Y, 1); + + // set default cursor options + setCursor(true, true, 2.0, 0.1); +} + +GUIChatConsole::~GUIChatConsole() +{ + if (m_font) + m_font->drop(); +} + +void GUIChatConsole::openConsole(f32 height) +{ + m_open = true; + m_desired_height_fraction = height; + m_desired_height = height * m_screensize.Y; + reformatConsole(); + m_animate_time_old = getTimeMs(); + IGUIElement::setVisible(true); + Environment->setFocus(this); + m_menumgr->createdMenu(this); +} + +bool GUIChatConsole::isOpen() const +{ + return m_open; +} + +bool GUIChatConsole::isOpenInhibited() const +{ + return m_open_inhibited > 0; +} + +void GUIChatConsole::closeConsole() +{ + m_open = false; + Environment->removeFocus(this); + m_menumgr->deletingMenu(this); +} + +void GUIChatConsole::closeConsoleAtOnce() +{ + closeConsole(); + m_height = 0; + recalculateConsolePosition(); +} + +f32 GUIChatConsole::getDesiredHeight() const +{ + return m_desired_height_fraction; +} + +void GUIChatConsole::replaceAndAddToHistory(std::wstring line) +{ + ChatPrompt& prompt = m_chat_backend->getPrompt(); + prompt.addToHistory(prompt.getLine()); + prompt.replace(line); +} + + +void GUIChatConsole::setCursor( + bool visible, bool blinking, f32 blink_speed, f32 relative_height) +{ + if (visible) + { + if (blinking) + { + // leave m_cursor_blink unchanged + m_cursor_blink_speed = blink_speed; + } + else + { + m_cursor_blink = 0x8000; // on + m_cursor_blink_speed = 0.0; + } + } + else + { + m_cursor_blink = 0; // off + m_cursor_blink_speed = 0.0; + } + m_cursor_height = relative_height; +} + +void GUIChatConsole::draw() +{ + if(!IsVisible) + return; + + video::IVideoDriver* driver = Environment->getVideoDriver(); + + // Check screen size + v2u32 screensize = driver->getScreenSize(); + if (screensize != m_screensize) + { + // screen size has changed + // scale current console height to new window size + if (m_screensize.Y != 0) + m_height = m_height * screensize.Y / m_screensize.Y; + m_desired_height = m_desired_height_fraction * m_screensize.Y; + m_screensize = screensize; + reformatConsole(); + } + + // Animation + u32 now = getTimeMs(); + animate(now - m_animate_time_old); + m_animate_time_old = now; + + // Draw console elements if visible + if (m_height > 0) + { + drawBackground(); + drawText(); + drawPrompt(); + } + + gui::IGUIElement::draw(); +} + +void GUIChatConsole::reformatConsole() +{ + s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) + s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt + if (cols <= 0 || rows <= 0) + cols = rows = 0; + m_chat_backend->reformat(cols, rows); +} + +void GUIChatConsole::recalculateConsolePosition() +{ + core::rect rect(0, 0, m_screensize.X, m_height); + DesiredRect = rect; + recalculateAbsolutePosition(false); +} + +void GUIChatConsole::animate(u32 msec) +{ + // animate the console height + s32 goal = m_open ? m_desired_height : 0; + + // Set invisible if close animation finished (reset by openConsole) + // This function (animate()) is never called once its visibility becomes false so do not + // actually set visible to false before the inhibited period is over + if (!m_open && m_height == 0 && m_open_inhibited == 0) + IGUIElement::setVisible(false); + + if (m_height != goal) + { + s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); + if (max_change == 0) + max_change = 1; + + if (m_height < goal) + { + // increase height + if (m_height + max_change < goal) + m_height += max_change; + else + m_height = goal; + } + else + { + // decrease height + if (m_height > goal + max_change) + m_height -= max_change; + else + m_height = goal; + } + + recalculateConsolePosition(); + } + + // blink the cursor + if (m_cursor_blink_speed != 0.0) + { + u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); + if (blink_increase == 0) + blink_increase = 1; + m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff); + } + + // decrease open inhibit counter + if (m_open_inhibited > msec) + m_open_inhibited -= msec; + else + m_open_inhibited = 0; +} + +void GUIChatConsole::drawBackground() +{ + video::IVideoDriver* driver = Environment->getVideoDriver(); + if (m_background != NULL) + { + core::rect sourcerect(0, -m_height, m_screensize.X, 0); + driver->draw2DImage( + m_background, + v2s32(0, 0), + sourcerect, + &AbsoluteClippingRect, + m_background_color, + false); + } + else + { + driver->draw2DRectangle( + m_background_color, + core::rect(0, 0, m_screensize.X, m_height), + &AbsoluteClippingRect); + } +} + +void GUIChatConsole::drawText() +{ + if (m_font == NULL) + return; + + ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); + for (u32 row = 0; row < buf.getRows(); ++row) + { + const ChatFormattedLine& line = buf.getFormattedLine(row); + if (line.fragments.empty()) + continue; + + s32 line_height = m_fontsize.Y; + s32 y = row * line_height + m_height - m_desired_height; + if (y + line_height < 0) + continue; + + for (u32 i = 0; i < line.fragments.size(); ++i) + { + const ChatFormattedFragment& fragment = line.fragments[i]; + s32 x = (fragment.column + 1) * m_fontsize.X; + core::rect destrect( + x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); + + + #if USE_FREETYPE + // Draw colored text if FreeType is enabled + irr::gui::CGUITTFont *tmp = static_cast(m_font); + tmp->draw( + fragment.text, + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); + #else + // Otherwise use standard text + m_font->draw( + fragment.text.c_str(), + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); + #endif + } + } +} + +void GUIChatConsole::drawPrompt() +{ + if (m_font == NULL) + return; + + u32 row = m_chat_backend->getConsoleBuffer().getRows(); + s32 line_height = m_fontsize.Y; + s32 y = row * line_height + m_height - m_desired_height; + + ChatPrompt& prompt = m_chat_backend->getPrompt(); + std::wstring prompt_text = prompt.getVisiblePortion(); + + // FIXME Draw string at once, not character by character + // That will only work with the cursor once we have a monospace font + for (u32 i = 0; i < prompt_text.size(); ++i) + { + wchar_t ws[2] = {prompt_text[i], 0}; + s32 x = (1 + i) * m_fontsize.X; + core::rect destrect( + x, y, x + m_fontsize.X, y + m_fontsize.Y); + m_font->draw( + ws, + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); + } + + // Draw the cursor during on periods + if ((m_cursor_blink & 0x8000) != 0) + { + s32 cursor_pos = prompt.getVisibleCursorPosition(); + if (cursor_pos >= 0) + { + s32 cursor_len = prompt.getCursorLength(); + video::IVideoDriver* driver = Environment->getVideoDriver(); + s32 x = (1 + cursor_pos) * m_fontsize.X; + core::rect destrect( + x, + y + m_fontsize.Y * (1.0 - m_cursor_height), + x + m_fontsize.X * MYMAX(cursor_len, 1), + y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) + ); + video::SColor cursor_color(255,255,255,255); + driver->draw2DRectangle( + cursor_color, + destrect, + &AbsoluteClippingRect); + } + } + +} + +bool GUIChatConsole::OnEvent(const SEvent& event) +{ + + ChatPrompt &prompt = m_chat_backend->getPrompt(); + + if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) + { + // Key input + if(KeyPress(event.KeyInput) == getKeySetting("keymap_console")) + { + closeConsole(); + + // inhibit open so the_game doesn't reopen immediately + m_open_inhibited = 50; + m_close_on_enter = false; + return true; + } + else if(event.KeyInput.Key == KEY_ESCAPE) + { + closeConsoleAtOnce(); + m_close_on_enter = false; + // inhibit open so the_game doesn't reopen immediately + m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" + return true; + } + else if(event.KeyInput.Key == KEY_PRIOR) + { + m_chat_backend->scrollPageUp(); + return true; + } + else if(event.KeyInput.Key == KEY_NEXT) + { + m_chat_backend->scrollPageDown(); + return true; + } + else if(event.KeyInput.Key == KEY_RETURN) + { + prompt.addToHistory(prompt.getLine()); + std::wstring text = prompt.replace(L""); + m_client->typeChatMessage(text); + if (m_close_on_enter) { + closeConsoleAtOnce(); + m_close_on_enter = false; + } + return true; + } + else if(event.KeyInput.Key == KEY_UP) + { + // Up pressed + // Move back in history + prompt.historyPrev(); + return true; + } + else if(event.KeyInput.Key == KEY_DOWN) + { + // Down pressed + // Move forward in history + prompt.historyNext(); + return true; + } + else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) + { + // Left/right pressed + // Move/select character/word to the left depending on control and shift keys + ChatPrompt::CursorOp op = event.KeyInput.Shift ? + ChatPrompt::CURSOROP_SELECT : + ChatPrompt::CURSOROP_MOVE; + ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? + ChatPrompt::CURSOROP_DIR_LEFT : + ChatPrompt::CURSOROP_DIR_RIGHT; + ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation(op, dir, scope); + return true; + } + else if(event.KeyInput.Key == KEY_HOME) + { + // Home pressed + // move to beginning of line + prompt.cursorOperation( + ChatPrompt::CURSOROP_MOVE, + ChatPrompt::CURSOROP_DIR_LEFT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_END) + { + // End pressed + // move to end of line + prompt.cursorOperation( + ChatPrompt::CURSOROP_MOVE, + ChatPrompt::CURSOROP_DIR_RIGHT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_BACK) + { + // Backspace or Ctrl-Backspace pressed + // delete character / word to the left + ChatPrompt::CursorOpScope scope = + event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, + scope); + return true; + } + else if(event.KeyInput.Key == KEY_DELETE) + { + // Delete or Ctrl-Delete pressed + // delete character / word to the right + ChatPrompt::CursorOpScope scope = + event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_RIGHT, + scope); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) + { + // Ctrl-A pressed + // Select all text + prompt.cursorOperation( + ChatPrompt::CURSOROP_SELECT, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) + { + // Ctrl-C pressed + // Copy text to clipboard + if (prompt.getCursorLength() <= 0) + return true; + std::wstring wselected = prompt.getSelection(); + std::string selected(wselected.begin(), wselected.end()); + Environment->getOSOperator()->copyToClipboard(selected.c_str()); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) + { + // Ctrl-V pressed + // paste text from clipboard + if (prompt.getCursorLength() > 0) { + // Delete selected section of text + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_SELECTION); + } + IOSOperator *os_operator = Environment->getOSOperator(); + const c8 *text = os_operator->getTextFromClipboard(); + if (!text) + return true; + std::basic_string str((const unsigned char*)text); + prompt.input(std::wstring(str.begin(), str.end())); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) + { + // Ctrl-X pressed + // Cut text to clipboard + if (prompt.getCursorLength() <= 0) + return true; + std::wstring wselected = prompt.getSelection(); + std::string selected(wselected.begin(), wselected.end()); + Environment->getOSOperator()->copyToClipboard(selected.c_str()); + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_SELECTION); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) + { + // Ctrl-U pressed + // kill line to left end + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) + { + // Ctrl-K pressed + // kill line to right end + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_RIGHT, + ChatPrompt::CURSOROP_SCOPE_LINE); + return true; + } + else if(event.KeyInput.Key == KEY_TAB) + { + // Tab or Shift-Tab pressed + // Nick completion + std::list names = m_client->getConnectedPlayerNames(); + bool backwards = event.KeyInput.Shift; + prompt.nickCompletion(names, backwards); + return true; + } + else if(event.KeyInput.Char != 0 && !event.KeyInput.Control) + { + #if (defined(linux) || defined(__linux)) + wchar_t wc = L'_'; + mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); + prompt.input(wc); + #else + prompt.input(event.KeyInput.Char); + #endif + return true; + } + } + else if(event.EventType == EET_MOUSE_INPUT_EVENT) + { + if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) + { + s32 rows = myround(-3.0 * event.MouseInput.Wheel); + m_chat_backend->scroll(rows); + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + +void GUIChatConsole::setVisible(bool visible) +{ + m_open = visible; + IGUIElement::setVisible(visible); + if (!visible) { + m_height = 0; + recalculateConsolePosition(); + } +} + diff --git a/src/guiChatConsole.h b/src/guiChatConsole.h new file mode 100644 index 000000000..3013a1d31 --- /dev/null +++ b/src/guiChatConsole.h @@ -0,0 +1,138 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GUICHATCONSOLE_HEADER +#define GUICHATCONSOLE_HEADER + +#include "irrlichttypes_extrabloated.h" +#include "modalMenu.h" +#include "chat.h" +#include "config.h" + +class Client; + +class GUIChatConsole : public gui::IGUIElement +{ +public: + GUIChatConsole(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, + s32 id, + ChatBackend* backend, + Client* client, + IMenuManager* menumgr); + virtual ~GUIChatConsole(); + + // Open the console (height = desired fraction of screen size) + // This doesn't open immediately but initiates an animation. + // You should call isOpenInhibited() before this. + void openConsole(f32 height); + + bool isOpen() const; + + // Check if the console should not be opened at the moment + // This is to avoid reopening the console immediately after closing + bool isOpenInhibited() const; + // Close the console, equivalent to openConsole(0). + // This doesn't close immediately but initiates an animation. + void closeConsole(); + // Close the console immediately, without animation. + void closeConsoleAtOnce(); + // Set whether to close the console after the user presses enter. + void setCloseOnEnter(bool close) { m_close_on_enter = close; } + + // Return the desired height (fraction of screen size) + // Zero if the console is closed or getting closed + f32 getDesiredHeight() const; + + // Replace actual line when adding the actual to the history (if there is any) + void replaceAndAddToHistory(std::wstring line); + + // Change how the cursor looks + void setCursor( + bool visible, + bool blinking = false, + f32 blink_speed = 1.0, + f32 relative_height = 1.0); + + // Irrlicht draw method + virtual void draw(); + + bool canTakeFocus(gui::IGUIElement* element) { return false; } + + virtual bool OnEvent(const SEvent& event); + + virtual void setVisible(bool visible); + +private: + void reformatConsole(); + void recalculateConsolePosition(); + + // These methods are called by draw + void animate(u32 msec); + void drawBackground(); + void drawText(); + void drawPrompt(); + +private: + ChatBackend* m_chat_backend; + Client* m_client; + IMenuManager* m_menumgr; + + // current screen size + v2u32 m_screensize; + + // used to compute how much time passed since last animate() + u32 m_animate_time_old; + + // should the console be opened or closed? + bool m_open; + // should it close after you press enter? + bool m_close_on_enter; + // current console height [pixels] + s32 m_height; + // desired height [pixels] + f32 m_desired_height; + // desired height [screen height fraction] + f32 m_desired_height_fraction; + // console open/close animation speed [screen height fraction / second] + f32 m_height_speed; + // if nonzero, opening the console is inhibited [milliseconds] + u32 m_open_inhibited; + + // cursor blink frame (16-bit value) + // cursor is off during [0,32767] and on during [32768,65535] + u32 m_cursor_blink; + // cursor blink speed [on/off toggles / second] + f32 m_cursor_blink_speed; + // cursor height [line height] + f32 m_cursor_height; + + // background texture + video::ITexture* m_background; + // background color (including alpha) + video::SColor m_background_color; + + // font + gui::IGUIFont* m_font; + v2u32 m_fontsize; +}; + + +#endif + diff --git a/src/guiEngine.cpp b/src/guiEngine.cpp index ba286a91c..96de7a4f7 100644 --- a/src/guiEngine.cpp +++ b/src/guiEngine.cpp @@ -37,6 +37,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "fontengine.h" #include "guiscalingfilter.h" +#include "irrlicht_changes/static_text.h" #ifdef __ANDROID__ #include "client/tile.h" @@ -172,15 +173,16 @@ GUIEngine::GUIEngine( irr::IrrlichtDevice* dev, m_sound_manager = &dummySoundManager; //create topleft header - std::wstring t = utf8_to_wide(std::string(PROJECT_NAME_C " ") + + m_toplefttext = utf8_to_wide(std::string(PROJECT_NAME_C " ") + g_version_hash); - core::rect rect(0, 0, g_fontengine->getTextWidth(t), g_fontengine->getTextHeight()); + core::rect rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()), + g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext = - m_device->getGUIEnvironment()->addStaticText(t.c_str(), - rect,false,true,0,-1); + addStaticText(m_device->getGUIEnvironment(), m_toplefttext, + rect, false, true, 0, -1); //create formspecsource m_formspecgui = new FormspecFormSource(""); @@ -578,7 +580,7 @@ void GUIEngine::setTopleftText(std::string append) toset += utf8_to_wide(append); } - m_irr_toplefttext->setText(toset.c_str()); + m_toplefttext = toset; updateTopLeftTextSize(); } @@ -586,15 +588,14 @@ void GUIEngine::setTopleftText(std::string append) /******************************************************************************/ void GUIEngine::updateTopLeftTextSize() { - std::wstring text = m_irr_toplefttext->getText(); - - core::rect rect(0, 0, g_fontengine->getTextWidth(text), g_fontengine->getTextHeight()); - rect += v2s32(4, 0); + core::rect rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()), + g_fontengine->getTextHeight()); + rect += v2s32(4, 0); m_irr_toplefttext->remove(); m_irr_toplefttext = - m_device->getGUIEnvironment()->addStaticText(text.c_str(), - rect,false,true,0,-1); + addStaticText(m_device->getGUIEnvironment(), m_toplefttext, + rect, false, true, 0, -1); } /******************************************************************************/ diff --git a/src/guiEngine.h b/src/guiEngine.h index d527f7222..fa98a21e4 100644 --- a/src/guiEngine.h +++ b/src/guiEngine.h @@ -28,6 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiFormSpecMenu.h" #include "sound.h" #include "client/tile.h" +#include "util/enriched_string.h" /******************************************************************************/ /* Typedefs and macros */ @@ -275,6 +276,8 @@ private: /** pointer to gui element shown at topleft corner */ irr::gui::IGUIStaticText* m_irr_toplefttext; + /** and text that is in it */ + EnrichedString m_toplefttext; /** initialize cloud subsystem */ void cloudInit(); diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 99b1153c1..cf01dc38c 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -50,6 +50,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/hex.h" #include "util/numeric.h" #include "util/string.h" // for parseColorString() +#include "irrlicht_changes/static_text.h" #include "guiscalingfilter.h" #if USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9 @@ -249,37 +250,6 @@ std::vector* GUIFormSpecMenu::getDropDownValues(const std::string & return NULL; } -static std::vector split(const std::string &s, char delim) -{ - std::vector tokens; - - std::string current = ""; - bool last_was_escape = false; - for (unsigned int i = 0; i < s.size(); i++) { - char si = s.c_str()[i]; - if (last_was_escape) { - current += '\\'; - current += si; - last_was_escape = false; - } else { - if (si == delim) { - tokens.push_back(current); - current = ""; - last_was_escape = false; - } else if (si == '\\') { - last_was_escape = true; - } else { - current += si; - last_was_escape = false; - } - } - } - //push last element - tokens.push_back(current); - - return tokens; -} - void GUIFormSpecMenu::parseSize(parserData* data,std::string element) { std::vector parts = split(element,','); @@ -966,7 +936,7 @@ void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element) int font_height = g_fontengine->getTextHeight(); rect.UpperLeftCorner.Y -= font_height; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height; - Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0); + addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, 0); } e->setPasswordBox(true,L'*'); @@ -1021,7 +991,7 @@ void GUIFormSpecMenu::parseSimpleField(parserData* data, if (name == "") { // spec field id to 0, this stops submit searching for a value that isn't there - Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid); + addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid); } else { @@ -1056,7 +1026,7 @@ void GUIFormSpecMenu::parseSimpleField(parserData* data, int font_height = g_fontengine->getTextHeight(); rect.UpperLeftCorner.Y -= font_height; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height; - Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0); + addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, 0); } } @@ -1117,7 +1087,7 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, if (name == "") { // spec field id to 0, this stops submit searching for a value that isn't there - Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid); + addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid); } else { @@ -1161,7 +1131,7 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, int font_height = g_fontengine->getTextHeight(); rect.UpperLeftCorner.Y -= font_height; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height; - Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0); + addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, 0); } } m_fields.push_back(spec); @@ -1230,7 +1200,7 @@ void GUIFormSpecMenu::parseLabel(parserData* data,std::string element) 258+m_fields.size() ); gui::IGUIStaticText *e = - Environment->addStaticText(spec.flabel.c_str(), + addStaticText(Environment, spec.flabel.c_str(), rect, false, false, this, spec.fid); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER); @@ -1284,7 +1254,7 @@ void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element) 258+m_fields.size() ); gui::IGUIStaticText *t = - Environment->addStaticText(spec.flabel.c_str(), rect, false, false, this, spec.fid); + addStaticText(Environment, spec.flabel.c_str(), rect, false, false, this, spec.fid); t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); m_fields.push_back(spec); return; @@ -1910,7 +1880,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) { assert(m_tooltip_element == NULL); // Note: parent != this so that the tooltip isn't clipped by the menu rectangle - m_tooltip_element = Environment->addStaticText(L"",core::rect(0,0,110,18)); + m_tooltip_element = addStaticText(Environment, L"",core::rect(0,0,110,18)); m_tooltip_element->enableOverrideColor(true); m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor); m_tooltip_element->setDrawBackground(true); @@ -2255,7 +2225,6 @@ void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase, std::wstring tooltip_text = L""; if (hovering && !m_selected_item) { tooltip_text = utf8_to_wide(item.getDefinition(m_gamedef->idef()).description); - tooltip_text = unescape_enriched(tooltip_text); } if (tooltip_text != L"") { std::vector tt_rows = str_split(tooltip_text, L'\n'); @@ -2263,7 +2232,7 @@ void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase, m_tooltip_element->setOverrideColor(m_default_tooltip_color); m_tooltip_element->setVisible(true); this->bringToFront(m_tooltip_element); - m_tooltip_element->setText(tooltip_text.c_str()); + setStaticText(m_tooltip_element, tooltip_text.c_str()); s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height; #if IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2 s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5; @@ -2535,8 +2504,10 @@ void GUIFormSpecMenu::drawMenu() iter != m_fields.end(); ++iter) { if (iter->fid == id && m_tooltips[iter->fname].tooltip != L"") { if (m_old_tooltip != m_tooltips[iter->fname].tooltip) { + m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor); + m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color); m_old_tooltip = m_tooltips[iter->fname].tooltip; - m_tooltip_element->setText(m_tooltips[iter->fname].tooltip.c_str()); + setStaticText(m_tooltip_element, m_tooltips[iter->fname].tooltip.c_str()); std::vector tt_rows = str_split(m_tooltips[iter->fname].tooltip, L'\n'); s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height; s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5; @@ -2558,8 +2529,6 @@ void GUIFormSpecMenu::drawMenu() core::position2d(tooltip_x, tooltip_y), core::dimension2d(tooltip_width, tooltip_height))); } - m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor); - m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color); m_tooltip_element->setVisible(true); this->bringToFront(m_tooltip_element); break; @@ -2568,6 +2537,8 @@ void GUIFormSpecMenu::drawMenu() } } + m_tooltip_element->draw(); + /* Draw dragged item stack */ diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index ef230c81c..4122b1f56 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -30,6 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiTable.h" #include "network/networkprotocol.h" #include "util/string.h" +#include "util/enriched_string.h" class IGameDef; class InventoryManager; @@ -202,7 +203,8 @@ class GUIFormSpecMenu : public GUIModalMenu fname(name), fid(id) { - flabel = unescape_enriched(label); + //flabel = unescape_enriched(label); + flabel = label; fdefault = unescape_enriched(default_text); send = false; ftype = f_Unknown; @@ -239,7 +241,8 @@ class GUIFormSpecMenu : public GUIModalMenu bgcolor(a_bgcolor), color(a_color) { - tooltip = unescape_enriched(utf8_to_wide(a_tooltip)); + //tooltip = unescape_enriched(utf8_to_wide(a_tooltip)); + tooltip = utf8_to_wide(a_tooltip); } std::wstring tooltip; irr::video::SColor bgcolor; @@ -256,7 +259,8 @@ class GUIFormSpecMenu : public GUIModalMenu rect(a_rect), parent_button(NULL) { - text = unescape_enriched(a_text); + //text = unescape_enriched(a_text); + text = a_text; } StaticTextSpec(const std::wstring &a_text, const core::rect &a_rect, @@ -264,7 +268,8 @@ class GUIFormSpecMenu : public GUIModalMenu rect(a_rect), parent_button(a_parent_button) { - text = unescape_enriched(a_text); + //text = unescape_enriched(a_text); + text = a_text; } std::wstring text; core::rect rect; diff --git a/src/irrlicht_changes/CMakeLists.txt b/src/irrlicht_changes/CMakeLists.txt new file mode 100644 index 000000000..3a265c99d --- /dev/null +++ b/src/irrlicht_changes/CMakeLists.txt @@ -0,0 +1,7 @@ +if (BUILD_CLIENT) + set(client_irrlicht_changes_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/static_text.cpp + PARENT_SCOPE + ) +endif() + diff --git a/src/irrlicht_changes/static_text.cpp b/src/irrlicht_changes/static_text.cpp new file mode 100644 index 000000000..703287eb3 --- /dev/null +++ b/src/irrlicht_changes/static_text.cpp @@ -0,0 +1,679 @@ +// Copyright (C) 2002-2012 Nikolaus Gebhardt +// Copyright (C) 2016 Nathanaël Courant: +// Modified the functions to use EnrichedText instead of string. +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#include "static_text.h" +#ifdef _IRR_COMPILE_WITH_GUI_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if USE_FREETYPE + #include "cguittfont/xCGUITTFont.h" +#endif + +#include "util/string.h" + +namespace irr +{ + +#if USE_FREETYPE + +namespace gui +{ +//! constructor +StaticText::StaticText(const EnrichedString &text, bool border, + IGUIEnvironment* environment, IGUIElement* parent, + s32 id, const core::rect& rectangle, + bool background) +: IGUIStaticText(environment, parent, id, rectangle), + HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), + Border(border), OverrideColorEnabled(false), OverrideBGColorEnabled(false), WordWrap(false), Background(background), + RestrainTextInside(true), RightToLeft(false), + OverrideColor(video::SColor(101,255,255,255)), BGColor(video::SColor(101,210,210,210)), + OverrideFont(0), LastBreakFont(0) +{ + #ifdef _DEBUG + setDebugName("StaticText"); + #endif + + Text = text.c_str(); + cText = text; + if (environment && environment->getSkin()) + { + BGColor = environment->getSkin()->getColor(gui::EGDC_3D_FACE); + } +} + + +//! destructor +StaticText::~StaticText() +{ + if (OverrideFont) + OverrideFont->drop(); +} + +//! draws the element and its children +void StaticText::draw() +{ + if (!IsVisible) + return; + + IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + core::rect frameRect(AbsoluteRect); + + // draw background + + if (Background) + { + if ( !OverrideBGColorEnabled ) // skin-colors can change + BGColor = skin->getColor(gui::EGDC_3D_FACE); + + driver->draw2DRectangle(BGColor, frameRect, &AbsoluteClippingRect); + } + + // draw the border + + if (Border) + { + skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); + frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); + } + + // draw the text + if (cText.size()) + { + IGUIFont* font = getActiveFont(); + + if (font) + { + if (!WordWrap) + { + // TODO: add colors here + if (VAlign == EGUIA_LOWERRIGHT) + { + frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - + font->getDimension(L"A").Height - font->getKerningHeight(); + } + if (HAlign == EGUIA_LOWERRIGHT) + { + frameRect.UpperLeftCorner.X = frameRect.LowerRightCorner.X - + font->getDimension(cText.c_str()).Width; + } + + irr::gui::CGUITTFont *tmp = static_cast(font); + tmp->draw(cText, frameRect, + OverrideColorEnabled ? OverrideColor : skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT), + HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); + } + else + { + if (font != LastBreakFont) + breakText(); + + core::rect r = frameRect; + s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); + s32 totalHeight = height * BrokenText.size(); + if (VAlign == EGUIA_CENTER) + { + r.UpperLeftCorner.Y = r.getCenter().Y - (totalHeight / 2); + } + else if (VAlign == EGUIA_LOWERRIGHT) + { + r.UpperLeftCorner.Y = r.LowerRightCorner.Y - totalHeight; + } + + irr::video::SColor previous_color(255, 255, 255, 255); + for (u32 i=0; igetDimension(BrokenText[i].c_str()).Width; + } + + //std::vector colors; + //std::wstring str; + EnrichedString str = BrokenText[i]; + + //str = colorizeText(BrokenText[i].c_str(), colors, previous_color); + //if (!colors.empty()) + // previous_color = colors[colors.size() - 1]; + + irr::gui::CGUITTFont *tmp = static_cast(font); + tmp->draw(str, r, + previous_color, // FIXME + HAlign == EGUIA_CENTER, false, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); + + r.LowerRightCorner.Y += height; + r.UpperLeftCorner.Y += height; + } + } + } + } + + IGUIElement::draw(); +} + + +//! Sets another skin independent font. +void StaticText::setOverrideFont(IGUIFont* font) +{ + if (OverrideFont == font) + return; + + if (OverrideFont) + OverrideFont->drop(); + + OverrideFont = font; + + if (OverrideFont) + OverrideFont->grab(); + + breakText(); +} + +//! Gets the override font (if any) +IGUIFont * StaticText::getOverrideFont() const +{ + return OverrideFont; +} + +//! Get the font which is used right now for drawing +IGUIFont* StaticText::getActiveFont() const +{ + if ( OverrideFont ) + return OverrideFont; + IGUISkin* skin = Environment->getSkin(); + if (skin) + return skin->getFont(); + return 0; +} + +//! Sets another color for the text. +void StaticText::setOverrideColor(video::SColor color) +{ + OverrideColor = color; + OverrideColorEnabled = true; +} + + +//! Sets another color for the text. +void StaticText::setBackgroundColor(video::SColor color) +{ + BGColor = color; + OverrideBGColorEnabled = true; + Background = true; +} + + +//! Sets whether to draw the background +void StaticText::setDrawBackground(bool draw) +{ + Background = draw; +} + + +//! Gets the background color +video::SColor StaticText::getBackgroundColor() const +{ + return BGColor; +} + + +//! Checks if background drawing is enabled +bool StaticText::isDrawBackgroundEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return Background; +} + + +//! Sets whether to draw the border +void StaticText::setDrawBorder(bool draw) +{ + Border = draw; +} + + +//! Checks if border drawing is enabled +bool StaticText::isDrawBorderEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return Border; +} + + +void StaticText::setTextRestrainedInside(bool restrainTextInside) +{ + RestrainTextInside = restrainTextInside; +} + + +bool StaticText::isTextRestrainedInside() const +{ + return RestrainTextInside; +} + + +void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) +{ + HAlign = horizontal; + VAlign = vertical; +} + + +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 +const video::SColor& StaticText::getOverrideColor() const +#else +video::SColor StaticText::getOverrideColor() const +#endif +{ + return OverrideColor; +} + + +//! Sets if the static text should use the overide color or the +//! color in the gui skin. +void StaticText::enableOverrideColor(bool enable) +{ + OverrideColorEnabled = enable; +} + + +bool StaticText::isOverrideColorEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return OverrideColorEnabled; +} + + +//! Enables or disables word wrap for using the static text as +//! multiline text control. +void StaticText::setWordWrap(bool enable) +{ + WordWrap = enable; + breakText(); +} + + +bool StaticText::isWordWrapEnabled() const +{ + _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; + return WordWrap; +} + + +void StaticText::setRightToLeft(bool rtl) +{ + if (RightToLeft != rtl) + { + RightToLeft = rtl; + breakText(); + } +} + + +bool StaticText::isRightToLeft() const +{ + return RightToLeft; +} + + +//! Breaks the single text line. +void StaticText::breakText() +{ + if (!WordWrap) + return; + + BrokenText.clear(); + + IGUISkin* skin = Environment->getSkin(); + IGUIFont* font = getActiveFont(); + if (!font) + return; + + LastBreakFont = font; + + EnrichedString line; + EnrichedString word; + EnrichedString whitespace; + s32 size = cText.size(); + s32 length = 0; + s32 elWidth = RelativeRect.getWidth(); + if (Border) + elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X); + wchar_t c; + + //std::vector colors; + + // We have to deal with right-to-left and left-to-right differently + // However, most parts of the following code is the same, it's just + // some order and boundaries which change. + if (!RightToLeft) + { + // regular (left-to-right) + for (s32 i=0; igetDimension(whitespace.c_str()).Width; + //const std::wstring sanitized = removeEscapes(word.c_str()); + const s32 wordlgth = font->getDimension(word.c_str()).Width; + + if (wordlgth > elWidth) + { + // This word is too long to fit in the available space, look for + // the Unicode Soft HYphen (SHY / 00AD) character for a place to + // break the word at + int where = core::stringw(word.c_str()).findFirst( wchar_t(0x00AD) ); + if (where != -1) + { + EnrichedString first = word.substr(0, where); + EnrichedString second = word.substr(where, word.size() - where); + first.addCharNoColor(L'-'); + BrokenText.push_back(line + first); + const s32 secondLength = font->getDimension(second.c_str()).Width; + + length = secondLength; + line = second; + } + else + { + // No soft hyphen found, so there's nothing more we can do + // break to next line + if (length) + BrokenText.push_back(line); + length = wordlgth; + line = word; + } + } + else if (length && (length + wordlgth + whitelgth > elWidth)) + { + // break to next line + BrokenText.push_back(line); + length = wordlgth; + line = word; + } + else + { + // add word to line + line += whitespace; + line += word; + length += whitelgth + wordlgth; + } + + word.clear(); + whitespace.clear(); + } + + if ( isWhitespace && c != 0) + { + whitespace.addChar(cText, i); + } + + // compute line break + if (lineBreak) + { + line += whitespace; + line += word; + BrokenText.push_back(line); + line.clear(); + word.clear(); + whitespace.clear(); + length = 0; + } + } + } + + line += whitespace; + line += word; + BrokenText.push_back(line); + } + else + { + // right-to-left + for (s32 i=size; i>=0; --i) + { + c = cText.getString()[i]; + bool lineBreak = false; + + if (c == L'\r') // Mac or Windows breaks + { + lineBreak = true; + //if ((i>0) && Text[i-1] == L'\n') // Windows breaks + //{ + // Text.erase(i-1); + // --size; + //} + c = '\0'; + } + else if (c == L'\n') // Unix breaks + { + lineBreak = true; + c = '\0'; + } + + if (c==L' ' || c==0 || i==0) + { + if (word.size()) + { + // here comes the next whitespace, look if + // we must break the last word to the next line. + const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; + const s32 wordlgth = font->getDimension(word.c_str()).Width; + + if (length && (length + wordlgth + whitelgth > elWidth)) + { + // break to next line + BrokenText.push_back(line); + length = wordlgth; + line = word; + } + else + { + // add word to line + line = whitespace + line; + line = word + line; + length += whitelgth + wordlgth; + } + + word.clear(); + whitespace.clear(); + } + + if (c != 0) + // whitespace = core::stringw(&c, 1) + whitespace; + whitespace = cText.substr(i, 1) + whitespace; + + // compute line break + if (lineBreak) + { + line = whitespace + line; + line = word + line; + BrokenText.push_back(line); + line.clear(); + word.clear(); + whitespace.clear(); + length = 0; + } + } + else + { + // yippee this is a word.. + //word = core::stringw(&c, 1) + word; + word = cText.substr(i, 1) + word; + } + } + + line = whitespace + line; + line = word + line; + BrokenText.push_back(line); + } +} + + +//! Sets the new caption of this element. +void StaticText::setText(const wchar_t* text) +{ + setText(EnrichedString(text)); +} + +//! Sets the new caption of this element. +void StaticText::setText(const EnrichedString &text) +{ + IGUIElement::setText(text.c_str()); + cText = text; + if (text.hasBackground()) { + setBackgroundColor(text.getBackground()); + } + breakText(); +} + + +void StaticText::updateAbsolutePosition() +{ + IGUIElement::updateAbsolutePosition(); + breakText(); +} + + +//! Returns the height of the text in pixels when it is drawn. +s32 StaticText::getTextHeight() const +{ + IGUIFont* font = getActiveFont(); + if (!font) + return 0; + + s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); + + if (WordWrap) + height *= BrokenText.size(); + + return height; +} + + +s32 StaticText::getTextWidth() const +{ + IGUIFont * font = getActiveFont(); + if(!font) + return 0; + + if(WordWrap) + { + s32 widest = 0; + + for(u32 line = 0; line < BrokenText.size(); ++line) + { + s32 width = font->getDimension(BrokenText[line].c_str()).Width; + + if(width > widest) + widest = width; + } + + return widest; + } + else + { + return font->getDimension(cText.c_str()).Width; + } +} + + +//! Writes attributes of the element. +//! Implement this to expose the attributes of your element for +//! scripting languages, editors, debuggers or xml serialization purposes. +void StaticText::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const +{ + IGUIStaticText::serializeAttributes(out,options); + + out->addBool ("Border", Border); + out->addBool ("OverrideColorEnabled",OverrideColorEnabled); + out->addBool ("OverrideBGColorEnabled",OverrideBGColorEnabled); + out->addBool ("WordWrap", WordWrap); + out->addBool ("Background", Background); + out->addBool ("RightToLeft", RightToLeft); + out->addBool ("RestrainTextInside", RestrainTextInside); + out->addColor ("OverrideColor", OverrideColor); + out->addColor ("BGColor", BGColor); + out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); + out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); + + // out->addFont ("OverrideFont", OverrideFont); +} + + +//! Reads attributes of the element +void StaticText::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) +{ + IGUIStaticText::deserializeAttributes(in,options); + + Border = in->getAttributeAsBool("Border"); + enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); + OverrideBGColorEnabled = in->getAttributeAsBool("OverrideBGColorEnabled"); + setWordWrap(in->getAttributeAsBool("WordWrap")); + Background = in->getAttributeAsBool("Background"); + RightToLeft = in->getAttributeAsBool("RightToLeft"); + RestrainTextInside = in->getAttributeAsBool("RestrainTextInside"); + OverrideColor = in->getAttributeAsColor("OverrideColor"); + BGColor = in->getAttributeAsColor("BGColor"); + + setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), + (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); + + // OverrideFont = in->getAttributeAsFont("OverrideFont"); +} + +} // end namespace gui + +#endif // USE_FREETYPE + +} // end namespace irr + + +#endif // _IRR_COMPILE_WITH_GUI_ diff --git a/src/irrlicht_changes/static_text.h b/src/irrlicht_changes/static_text.h new file mode 100644 index 000000000..408a12784 --- /dev/null +++ b/src/irrlicht_changes/static_text.h @@ -0,0 +1,268 @@ +// Copyright (C) 2002-2012 Nikolaus Gebhardt +// Copyright (C) 2016 Nathanaël Courant +// Modified this class to work with EnrichedStrings too +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#ifndef __C_GUI_STATIC_TEXT_H_INCLUDED__ +#define __C_GUI_STATIC_TEXT_H_INCLUDED__ + +#include "IrrCompileConfig.h" +#ifdef _IRR_COMPILE_WITH_GUI_ + +#include "IGUIStaticText.h" +#include "irrArray.h" + +#include "log.h" + +#include + +#include "util/enriched_string.h" +#include "config.h" +#include + +#if USE_FREETYPE + +namespace irr +{ + +namespace gui +{ + + const EGUI_ELEMENT_TYPE EGUIET_ENRICHED_STATIC_TEXT = (EGUI_ELEMENT_TYPE)(0x1000); + + class StaticText : public IGUIStaticText + { + public: + + //! constructor + StaticText(const EnrichedString &text, bool border, IGUIEnvironment* environment, + IGUIElement* parent, s32 id, const core::rect& rectangle, + bool background = false); + + //! destructor + virtual ~StaticText(); + + //! draws the element and its children + virtual void draw(); + + //! Sets another skin independent font. + virtual void setOverrideFont(IGUIFont* font=0); + + //! Gets the override font (if any) + virtual IGUIFont* getOverrideFont() const; + + //! Get the font which is used right now for drawing + virtual IGUIFont* getActiveFont() const; + + //! Sets another color for the text. + virtual void setOverrideColor(video::SColor color); + + //! Sets another color for the background. + virtual void setBackgroundColor(video::SColor color); + + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw); + + //! Gets the background color + virtual video::SColor getBackgroundColor() const; + + //! Checks if background drawing is enabled + virtual bool isDrawBackgroundEnabled() const; + + //! Sets whether to draw the border + virtual void setDrawBorder(bool draw); + + //! Checks if border drawing is enabled + virtual bool isDrawBorderEnabled() const; + + //! Sets alignment mode for text + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); + + //! Gets the override color + #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 + virtual const video::SColor& getOverrideColor() const; + #else + virtual video::SColor getOverrideColor() const; + #endif + + //! Sets if the static text should use the overide color or the + //! color in the gui skin. + virtual void enableOverrideColor(bool enable); + + //! Checks if an override color is enabled + virtual bool isOverrideColorEnabled() const; + + //! Set whether the text in this label should be clipped if it goes outside bounds + virtual void setTextRestrainedInside(bool restrainedInside); + + //! Checks if the text in this label should be clipped if it goes outside bounds + virtual bool isTextRestrainedInside() const; + + //! Enables or disables word wrap for using the static text as + //! multiline text control. + virtual void setWordWrap(bool enable); + + //! Checks if word wrap is enabled + virtual bool isWordWrapEnabled() const; + + //! Sets the new caption of this element. + virtual void setText(const wchar_t* text); + + //! Returns the height of the text in pixels when it is drawn. + virtual s32 getTextHeight() const; + + //! Returns the width of the current text, in the current font + virtual s32 getTextWidth() const; + + //! Updates the absolute position, splits text if word wrap is enabled + virtual void updateAbsolutePosition(); + + //! Set whether the string should be interpreted as right-to-left (RTL) text + /** \note This component does not implement the Unicode bidi standard, the + text of the component should be already RTL if you call this. The + main difference when RTL is enabled is that the linebreaks for multiline + elements are performed starting from the end. + */ + virtual void setRightToLeft(bool rtl); + + //! Checks if the text should be interpreted as right-to-left text + virtual bool isRightToLeft() const; + + //! Writes attributes of the element. + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; + + //! Reads attributes of the element + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); + + virtual bool hasType(EGUI_ELEMENT_TYPE t) const { + return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); + }; + + virtual bool hasType(EGUI_ELEMENT_TYPE t) { + return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); + }; + + void setText(const EnrichedString &text); + + private: + + //! Breaks the single text line. + void breakText(); + + EGUI_ALIGNMENT HAlign, VAlign; + bool Border; + bool OverrideColorEnabled; + bool OverrideBGColorEnabled; + bool WordWrap; + bool Background; + bool RestrainTextInside; + bool RightToLeft; + + video::SColor OverrideColor, BGColor; + gui::IGUIFont* OverrideFont; + gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated. + + EnrichedString cText; + core::array< EnrichedString > BrokenText; + }; + + +} // end namespace gui + +} // end namespace irr + +inline irr::gui::IGUIStaticText *addStaticText( + irr::gui::IGUIEnvironment *guienv, + const EnrichedString &text, + const core::rect< s32 > &rectangle, + bool border = false, + bool wordWrap = true, + irr::gui::IGUIElement *parent = NULL, + s32 id = -1, + bool fillBackground = false) +{ + if (parent == NULL) { + // parent is NULL, so we must find one, or we need not to drop + // result, but then there will be a memory leak. + // + // What Irrlicht does is to use guienv as a parent, but the problem + // is that guienv is here only an IGUIEnvironment, while it is a + // CGUIEnvironment in Irrlicht, which inherits from both IGUIElement + // and IGUIEnvironment. + // + // A solution would be to dynamic_cast guienv to a + // IGUIElement*, but Irrlicht is shipped without rtti support + // in some distributions, causing the dymanic_cast to segfault. + // + // Thus, to find the parent, we create a dummy StaticText and ask + // for its parent, and then remove it. + irr::gui::IGUIStaticText *dummy_text = + guienv->addStaticText(L"", rectangle, border, wordWrap, + parent, id, fillBackground); + parent = dummy_text->getParent(); + dummy_text->remove(); + } + irr::gui::IGUIStaticText *result = new irr::gui::StaticText( + text, border, guienv, parent, + id, rectangle, fillBackground); + + result->setWordWrap(wordWrap); + result->drop(); + return result; +} + +inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) +{ + // dynamic_cast not possible due to some distributions shipped + // without rtti support in irrlicht + if (static_text->hasType(irr::gui::EGUIET_ENRICHED_STATIC_TEXT)) { + irr::gui::StaticText* stext = static_cast(static_text); + stext->setText(text); + } else { + static_text->setText(text.c_str()); + } +} + +#else // USE_FREETYPE + +inline irr::gui::IGUIStaticText *addStaticText( + irr::gui::IGUIEnvironment *guienv, + const EnrichedString &text, + const core::rect< s32 > &rectangle, + bool border = false, + bool wordWrap = true, + irr::gui::IGUIElement *parent = NULL, + s32 id = -1, + bool fillBackground = false) +{ + return guienv->addStaticText(text.c_str(), rectangle, border, wordWrap, parent, id, fillBackground); +} + +inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) +{ + static_text->setText(text.c_str()); +} + +#endif + +inline irr::gui::IGUIStaticText *addStaticText( + irr::gui::IGUIEnvironment *guienv, + const wchar_t *text, + const core::rect< s32 > &rectangle, + bool border = false, + bool wordWrap = true, + irr::gui::IGUIElement *parent = NULL, + s32 id = -1, + bool fillBackground = false) { + return addStaticText(guienv, EnrichedString(text), rectangle, border, wordWrap, parent, id, fillBackground); +} + +inline void setStaticText(irr::gui::IGUIStaticText *static_text, const wchar_t *text) +{ + setStaticText(static_text, EnrichedString(text)); +} + +#endif // _IRR_COMPILE_WITH_GUI_ + +#endif // C_GUI_STATIC_TEXT_H_INCLUDED diff --git a/src/terminal_chat_console.cpp b/src/terminal_chat_console.cpp index c86a960fa..a8c4ebaef 100644 --- a/src/terminal_chat_console.cpp +++ b/src/terminal_chat_console.cpp @@ -345,9 +345,11 @@ void TerminalChatConsole::step(int ch) if (p.first > m_log_level) continue; - m_chat_backend.addMessage( - utf8_to_wide(Logger::getLevelLabel(p.first)), - utf8_to_wide(p.second)); + std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first)); + if (!g_settings->getBool("disable_escape_sequences")) { + error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)"; + } + m_chat_backend.addMessage(error_message, utf8_to_wide(p.second)); } // handle input @@ -438,7 +440,7 @@ void TerminalChatConsole::draw_text() continue; for (u32 i = 0; i < line.fragments.size(); ++i) { const ChatFormattedFragment& fragment = line.fragments[i]; - addstr(wide_to_utf8(fragment.text).c_str()); + addstr(wide_to_utf8(fragment.text.getString()).c_str()); } } } diff --git a/src/util/CMakeLists.txt b/src/util/CMakeLists.txt index e028a0435..f571ab22c 100644 --- a/src/util/CMakeLists.txt +++ b/src/util/CMakeLists.txt @@ -1,17 +1,9 @@ -if(USE_FREETYPE) - set(UTIL_FREETYPEDEP_SRCS - ${CMAKE_CURRENT_SOURCE_DIR}/statictext.cpp - ) -else() - set(UTIL_FREETYPEDEP_SRCS ) -endif(USE_FREETYPE) - set(UTIL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/areastore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/auth.cpp ${CMAKE_CURRENT_SOURCE_DIR}/base64.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/coloredstring.cpp ${CMAKE_CURRENT_SOURCE_DIR}/directiontables.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/enriched_string.cpp ${CMAKE_CURRENT_SOURCE_DIR}/numeric.cpp ${CMAKE_CURRENT_SOURCE_DIR}/pointedthing.cpp ${CMAKE_CURRENT_SOURCE_DIR}/serialize.cpp @@ -20,6 +12,5 @@ set(UTIL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/string.cpp ${CMAKE_CURRENT_SOURCE_DIR}/srp.cpp ${CMAKE_CURRENT_SOURCE_DIR}/timetaker.cpp - ${UTIL_FREETYPEDEP_SRCS} PARENT_SCOPE) diff --git a/src/util/coloredstring.cpp b/src/util/coloredstring.cpp deleted file mode 100644 index 7db586550..000000000 --- a/src/util/coloredstring.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright (C) 2013 xyz, Ilya Zhuravlev - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#include "coloredstring.h" -#include "util/string.h" - -ColoredString::ColoredString() -{} - -ColoredString::ColoredString(const std::wstring &string, const std::vector &colors): - m_string(string), - m_colors(colors) -{} - -ColoredString::ColoredString(const std::wstring &s) { - m_string = colorizeText(s, m_colors, SColor(255, 255, 255, 255)); -} - -void ColoredString::operator=(const wchar_t *str) { - m_string = colorizeText(str, m_colors, SColor(255, 255, 255, 255)); -} - -size_t ColoredString::size() const { - return m_string.size(); -} - -ColoredString ColoredString::substr(size_t pos, size_t len) const { - if (pos == m_string.length()) - return ColoredString(); - if (len == std::string::npos || pos + len > m_string.length()) { - return ColoredString( - m_string.substr(pos, std::string::npos), - std::vector(m_colors.begin() + pos, m_colors.end()) - ); - } else { - return ColoredString( - m_string.substr(pos, len), - std::vector(m_colors.begin() + pos, m_colors.begin() + pos + len) - ); - } -} - -const wchar_t *ColoredString::c_str() const { - return m_string.c_str(); -} - -const std::vector &ColoredString::getColors() const { - return m_colors; -} - -const std::wstring &ColoredString::getString() const { - return m_string; -} diff --git a/src/util/coloredstring.h b/src/util/coloredstring.h deleted file mode 100644 index a6d98db30..000000000 --- a/src/util/coloredstring.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (C) 2013 xyz, Ilya Zhuravlev - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#ifndef COLOREDSTRING_HEADER -#define COLOREDSTRING_HEADER - -#include -#include -#include - -using namespace irr::video; - -class ColoredString { -public: - ColoredString(); - ColoredString(const std::wstring &s); - ColoredString(const std::wstring &string, const std::vector &colors); - void operator=(const wchar_t *str); - size_t size() const; - ColoredString substr(size_t pos = 0, size_t len = std::string::npos) const; - const wchar_t *c_str() const; - const std::vector &getColors() const; - const std::wstring &getString() const; -private: - std::wstring m_string; - std::vector m_colors; -}; - -#endif diff --git a/src/util/enriched_string.cpp b/src/util/enriched_string.cpp new file mode 100644 index 000000000..a7fc3a828 --- /dev/null +++ b/src/util/enriched_string.cpp @@ -0,0 +1,166 @@ +/* +Copyright (C) 2013 xyz, Ilya Zhuravlev +Copyright (C) 2016 Nore, Nathanaël Courant + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "enriched_string.h" +#include "util/string.h" +#include "log.h" +using namespace irr::video; + +EnrichedString::EnrichedString() +{ + clear(); +} + +EnrichedString::EnrichedString(const std::wstring &string, + const std::vector &colors): + m_string(string), + m_colors(colors), + m_has_background(false) +{} + +EnrichedString::EnrichedString(const std::wstring &s, const SColor &color) +{ + clear(); + addAtEnd(s, color); +} + +EnrichedString::EnrichedString(const wchar_t *str, const SColor &color) +{ + clear(); + addAtEnd(std::wstring(str), color); +} + +void EnrichedString::operator=(const wchar_t *str) +{ + clear(); + addAtEnd(std::wstring(str), SColor(255, 255, 255, 255)); +} + +void EnrichedString::addAtEnd(const std::wstring &s, const SColor &initial_color) +{ + SColor color(initial_color); + size_t i = 0; + while (i < s.length()) { + if (s[i] != L'\x1b') { + m_string += s[i]; + m_colors.push_back(color); + ++i; + continue; + } + ++i; + size_t start_index = i; + size_t length; + if (i == s.length()) { + break; + } + if (s[i] == L'(') { + ++i; + ++start_index; + while (i < s.length() && s[i] != L')') { + if (s[i] == L'\\') { + ++i; + } + ++i; + } + length = i - start_index; + ++i; + } else { + ++i; + length = 1; + } + std::wstring escape_sequence(s, start_index, length); + std::vector parts = split(escape_sequence, L'@'); + if (parts[0] == L"c") { + if (parts.size() < 2) { + continue; + } + parseColorString(wide_to_utf8(parts[1]), color, true); + } else if (parts[0] == L"b") { + if (parts.size() < 2) { + continue; + } + parseColorString(wide_to_utf8(parts[1]), m_background, true); + m_has_background = true; + } + continue; + } +} + +void EnrichedString::addChar(const EnrichedString &source, size_t i) +{ + m_string += source.m_string[i]; + m_colors.push_back(source.m_colors[i]); +} + +void EnrichedString::addCharNoColor(wchar_t c) +{ + m_string += c; + if (m_colors.empty()) { + m_colors.push_back(SColor(255, 255, 255, 255)); + } else { + m_colors.push_back(m_colors[m_colors.size() - 1]); + } +} + +EnrichedString EnrichedString::operator+(const EnrichedString &other) const +{ + std::vector result; + result.insert(result.end(), m_colors.begin(), m_colors.end()); + result.insert(result.end(), other.m_colors.begin(), other.m_colors.end()); + return EnrichedString(m_string + other.m_string, result); +} + +void EnrichedString::operator+=(const EnrichedString &other) +{ + m_string += other.m_string; + m_colors.insert(m_colors.end(), other.m_colors.begin(), other.m_colors.end()); +} + +EnrichedString EnrichedString::substr(size_t pos, size_t len) const +{ + if (pos == m_string.length()) { + return EnrichedString(); + } + if (len == std::string::npos || pos + len > m_string.length()) { + return EnrichedString( + m_string.substr(pos, std::string::npos), + std::vector(m_colors.begin() + pos, m_colors.end()) + ); + } else { + return EnrichedString( + m_string.substr(pos, len), + std::vector(m_colors.begin() + pos, m_colors.begin() + pos + len) + ); + } +} + +const wchar_t *EnrichedString::c_str() const +{ + return m_string.c_str(); +} + +const std::vector &EnrichedString::getColors() const +{ + return m_colors; +} + +const std::wstring &EnrichedString::getString() const +{ + return m_string; +} diff --git a/src/util/enriched_string.h b/src/util/enriched_string.h new file mode 100644 index 000000000..1aca8948a --- /dev/null +++ b/src/util/enriched_string.h @@ -0,0 +1,91 @@ +/* +Copyright (C) 2013 xyz, Ilya Zhuravlev +Copyright (C) 2016 Nore, Nathanaël Courant + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef ENRICHEDSTRING_HEADER +#define ENRICHEDSTRING_HEADER + +#include +#include +#include + +class EnrichedString { +public: + EnrichedString(); + EnrichedString(const std::wstring &s, + const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); + EnrichedString(const wchar_t *str, + const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); + EnrichedString(const std::wstring &string, + const std::vector &colors); + void operator=(const wchar_t *str); + void addAtEnd(const std::wstring &s, const irr::video::SColor &color); + + // Adds the character source[i] at the end. + // An EnrichedString should always be able to be copied + // to the end of an existing EnrichedString that way. + void addChar(const EnrichedString &source, size_t i); + + // Adds a single character at the end, without specifying its + // color. The color used will be the one from the last character. + void addCharNoColor(wchar_t c); + + EnrichedString substr(size_t pos = 0, size_t len = std::string::npos) const; + EnrichedString operator+(const EnrichedString &other) const; + void operator+=(const EnrichedString &other); + const wchar_t *c_str() const; + const std::vector &getColors() const; + const std::wstring &getString() const; + inline bool operator==(const EnrichedString &other) const + { + return (m_string == other.m_string && m_colors == other.m_colors); + } + inline bool operator!=(const EnrichedString &other) const + { + return !(*this == other); + } + inline void clear() + { + m_string.clear(); + m_colors.clear(); + m_has_background = false; + } + inline bool empty() const + { + return m_string.empty(); + } + inline size_t size() const + { + return m_string.size(); + } + inline bool hasBackground() const + { + return m_has_background; + } + inline irr::video::SColor getBackground() const + { + return m_background; + } +private: + std::wstring m_string; + std::vector m_colors; + bool m_has_background; + irr::video::SColor m_background; +}; + +#endif diff --git a/src/util/statictext.cpp b/src/util/statictext.cpp deleted file mode 100644 index b534b560e..000000000 --- a/src/util/statictext.cpp +++ /dev/null @@ -1,654 +0,0 @@ -// Copyright (C) 2002-2012 Nikolaus Gebhardt -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#include "statictext.h" -#ifdef _IRR_COMPILE_WITH_GUI_ - -//Only compile this if freetype is enabled. - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cguittfont/xCGUITTFont.h" -#include "util/string.h" - -namespace irr -{ -namespace gui -{ -//! constructor -StaticText::StaticText(const wchar_t* text, bool border, - IGUIEnvironment* environment, IGUIElement* parent, - s32 id, const core::rect& rectangle, - bool background) -: IGUIStaticText(environment, parent, id, rectangle), - HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), - Border(border), OverrideColorEnabled(false), OverrideBGColorEnabled(false), WordWrap(false), Background(background), - RestrainTextInside(true), RightToLeft(false), - OverrideColor(video::SColor(101,255,255,255)), BGColor(video::SColor(101,210,210,210)), - OverrideFont(0), LastBreakFont(0) -{ - #ifdef _DEBUG - setDebugName("StaticText"); - #endif - - Text = text; - if (environment && environment->getSkin()) - { - BGColor = environment->getSkin()->getColor(gui::EGDC_3D_FACE); - } -} - - -//! destructor -StaticText::~StaticText() -{ - if (OverrideFont) - OverrideFont->drop(); -} - - -//! draws the element and its children -void StaticText::draw() -{ - if (!IsVisible) - return; - - IGUISkin* skin = Environment->getSkin(); - if (!skin) - return; - video::IVideoDriver* driver = Environment->getVideoDriver(); - - core::rect frameRect(AbsoluteRect); - - // draw background - - if (Background) - { - if ( !OverrideBGColorEnabled ) // skin-colors can change - BGColor = skin->getColor(gui::EGDC_3D_FACE); - - driver->draw2DRectangle(BGColor, frameRect, &AbsoluteClippingRect); - } - - // draw the border - - if (Border) - { - skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); - frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); - } - - // draw the text - if (Text.size()) - { - IGUIFont* font = getActiveFont(); - - if (font) - { - if (!WordWrap) - { - // TODO: add colors here - if (VAlign == EGUIA_LOWERRIGHT) - { - frameRect.UpperLeftCorner.Y = frameRect.LowerRightCorner.Y - - font->getDimension(L"A").Height - font->getKerningHeight(); - } - if (HAlign == EGUIA_LOWERRIGHT) - { - frameRect.UpperLeftCorner.X = frameRect.LowerRightCorner.X - - font->getDimension(Text.c_str()).Width; - } - - font->draw(Text.c_str(), frameRect, - OverrideColorEnabled ? OverrideColor : skin->getColor(isEnabled() ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT), - HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); - } - else - { - if (font != LastBreakFont) - breakText(); - - core::rect r = frameRect; - s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); - s32 totalHeight = height * BrokenText.size(); - if (VAlign == EGUIA_CENTER) - { - r.UpperLeftCorner.Y = r.getCenter().Y - (totalHeight / 2); - } - else if (VAlign == EGUIA_LOWERRIGHT) - { - r.UpperLeftCorner.Y = r.LowerRightCorner.Y - totalHeight; - } - - irr::video::SColor previous_color(255, 255, 255, 255); - for (u32 i=0; igetDimension(BrokenText[i].c_str()).Width; - } - - std::vector colors; - std::wstring str; - - str = colorizeText(BrokenText[i].c_str(), colors, previous_color); - if (!colors.empty()) - previous_color = colors[colors.size() - 1]; - - irr::gui::CGUITTFont *tmp = static_cast(font); - tmp->draw(str.c_str(), r, - colors, - HAlign == EGUIA_CENTER, false, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); - - r.LowerRightCorner.Y += height; - r.UpperLeftCorner.Y += height; - } - } - } - } - - IGUIElement::draw(); -} - - -//! Sets another skin independent font. -void StaticText::setOverrideFont(IGUIFont* font) -{ - if (OverrideFont == font) - return; - - if (OverrideFont) - OverrideFont->drop(); - - OverrideFont = font; - - if (OverrideFont) - OverrideFont->grab(); - - breakText(); -} - -//! Gets the override font (if any) -IGUIFont * StaticText::getOverrideFont() const -{ - return OverrideFont; -} - -//! Get the font which is used right now for drawing -IGUIFont* StaticText::getActiveFont() const -{ - if ( OverrideFont ) - return OverrideFont; - IGUISkin* skin = Environment->getSkin(); - if (skin) - return skin->getFont(); - return 0; -} - -//! Sets another color for the text. -void StaticText::setOverrideColor(video::SColor color) -{ - OverrideColor = color; - OverrideColorEnabled = true; -} - - -//! Sets another color for the text. -void StaticText::setBackgroundColor(video::SColor color) -{ - BGColor = color; - OverrideBGColorEnabled = true; - Background = true; -} - - -//! Sets whether to draw the background -void StaticText::setDrawBackground(bool draw) -{ - Background = draw; -} - - -//! Gets the background color -video::SColor StaticText::getBackgroundColor() const -{ - return BGColor; -} - - -//! Checks if background drawing is enabled -bool StaticText::isDrawBackgroundEnabled() const -{ - _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; - return Background; -} - - -//! Sets whether to draw the border -void StaticText::setDrawBorder(bool draw) -{ - Border = draw; -} - - -//! Checks if border drawing is enabled -bool StaticText::isDrawBorderEnabled() const -{ - _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; - return Border; -} - - -void StaticText::setTextRestrainedInside(bool restrainTextInside) -{ - RestrainTextInside = restrainTextInside; -} - - -bool StaticText::isTextRestrainedInside() const -{ - return RestrainTextInside; -} - - -void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) -{ - HAlign = horizontal; - VAlign = vertical; -} - - -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 -const video::SColor& StaticText::getOverrideColor() const -#else -video::SColor StaticText::getOverrideColor() const -#endif -{ - return OverrideColor; -} - - -//! Sets if the static text should use the overide color or the -//! color in the gui skin. -void StaticText::enableOverrideColor(bool enable) -{ - OverrideColorEnabled = enable; -} - - -bool StaticText::isOverrideColorEnabled() const -{ - _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; - return OverrideColorEnabled; -} - - -//! Enables or disables word wrap for using the static text as -//! multiline text control. -void StaticText::setWordWrap(bool enable) -{ - WordWrap = enable; - breakText(); -} - - -bool StaticText::isWordWrapEnabled() const -{ - _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; - return WordWrap; -} - - -void StaticText::setRightToLeft(bool rtl) -{ - if (RightToLeft != rtl) - { - RightToLeft = rtl; - breakText(); - } -} - - -bool StaticText::isRightToLeft() const -{ - return RightToLeft; -} - - -//! Breaks the single text line. -void StaticText::breakText() -{ - if (!WordWrap) - return; - - BrokenText.clear(); - - IGUISkin* skin = Environment->getSkin(); - IGUIFont* font = getActiveFont(); - if (!font) - return; - - LastBreakFont = font; - - core::stringw line; - core::stringw word; - core::stringw whitespace; - s32 size = Text.size(); - s32 length = 0; - s32 elWidth = RelativeRect.getWidth(); - if (Border) - elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X); - wchar_t c; - - std::vector colors; - - // We have to deal with right-to-left and left-to-right differently - // However, most parts of the following code is the same, it's just - // some order and boundaries which change. - if (!RightToLeft) - { - // regular (left-to-right) - for (s32 i=0; igetDimension(whitespace.c_str()).Width; - const std::wstring sanitized = removeEscapes(word.c_str()); - const s32 wordlgth = font->getDimension(sanitized.c_str()).Width; - - if (wordlgth > elWidth) - { - // This word is too long to fit in the available space, look for - // the Unicode Soft HYphen (SHY / 00AD) character for a place to - // break the word at - int where = word.findFirst( wchar_t(0x00AD) ); - if (where != -1) - { - core::stringw first = word.subString(0, where); - core::stringw second = word.subString(where, word.size() - where); - BrokenText.push_back(line + first + L"-"); - const s32 secondLength = font->getDimension(second.c_str()).Width; - - length = secondLength; - line = second; - } - else - { - // No soft hyphen found, so there's nothing more we can do - // break to next line - if (length) - BrokenText.push_back(line); - length = wordlgth; - line = word; - } - } - else if (length && (length + wordlgth + whitelgth > elWidth)) - { - // break to next line - BrokenText.push_back(line); - length = wordlgth; - line = word; - } - else - { - // add word to line - line += whitespace; - line += word; - length += whitelgth + wordlgth; - } - - word = L""; - whitespace = L""; - } - - if ( isWhitespace ) - { - whitespace += c; - } - - // compute line break - if (lineBreak) - { - line += whitespace; - line += word; - BrokenText.push_back(line); - line = L""; - word = L""; - whitespace = L""; - length = 0; - } - } - } - - line += whitespace; - line += word; - BrokenText.push_back(line); - } - else - { - // right-to-left - for (s32 i=size; i>=0; --i) - { - c = Text[i]; - bool lineBreak = false; - - if (c == L'\r') // Mac or Windows breaks - { - lineBreak = true; - if ((i>0) && Text[i-1] == L'\n') // Windows breaks - { - Text.erase(i-1); - --size; - } - c = '\0'; - } - else if (c == L'\n') // Unix breaks - { - lineBreak = true; - c = '\0'; - } - - if (c==L' ' || c==0 || i==0) - { - if (word.size()) - { - // here comes the next whitespace, look if - // we must break the last word to the next line. - const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; - const s32 wordlgth = font->getDimension(word.c_str()).Width; - - if (length && (length + wordlgth + whitelgth > elWidth)) - { - // break to next line - BrokenText.push_back(line); - length = wordlgth; - line = word; - } - else - { - // add word to line - line = whitespace + line; - line = word + line; - length += whitelgth + wordlgth; - } - - word = L""; - whitespace = L""; - } - - if (c != 0) - whitespace = core::stringw(&c, 1) + whitespace; - - // compute line break - if (lineBreak) - { - line = whitespace + line; - line = word + line; - BrokenText.push_back(line); - line = L""; - word = L""; - whitespace = L""; - length = 0; - } - } - else - { - // yippee this is a word.. - word = core::stringw(&c, 1) + word; - } - } - - line = whitespace + line; - line = word + line; - BrokenText.push_back(line); - } -} - - -//! Sets the new caption of this element. -void StaticText::setText(const wchar_t* text) -{ - IGUIElement::setText(text); - breakText(); -} - - -void StaticText::updateAbsolutePosition() -{ - IGUIElement::updateAbsolutePosition(); - breakText(); -} - - -//! Returns the height of the text in pixels when it is drawn. -s32 StaticText::getTextHeight() const -{ - IGUIFont* font = getActiveFont(); - if (!font) - return 0; - - s32 height = font->getDimension(L"A").Height + font->getKerningHeight(); - - if (WordWrap) - height *= BrokenText.size(); - - return height; -} - - -s32 StaticText::getTextWidth() const -{ - IGUIFont * font = getActiveFont(); - if(!font) - return 0; - - if(WordWrap) - { - s32 widest = 0; - - for(u32 line = 0; line < BrokenText.size(); ++line) - { - s32 width = font->getDimension(BrokenText[line].c_str()).Width; - - if(width > widest) - widest = width; - } - - return widest; - } - else - { - return font->getDimension(Text.c_str()).Width; - } -} - - -//! Writes attributes of the element. -//! Implement this to expose the attributes of your element for -//! scripting languages, editors, debuggers or xml serialization purposes. -void StaticText::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const -{ - IGUIStaticText::serializeAttributes(out,options); - - out->addBool ("Border", Border); - out->addBool ("OverrideColorEnabled",OverrideColorEnabled); - out->addBool ("OverrideBGColorEnabled",OverrideBGColorEnabled); - out->addBool ("WordWrap", WordWrap); - out->addBool ("Background", Background); - out->addBool ("RightToLeft", RightToLeft); - out->addBool ("RestrainTextInside", RestrainTextInside); - out->addColor ("OverrideColor", OverrideColor); - out->addColor ("BGColor", BGColor); - out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); - out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); - - // out->addFont ("OverrideFont", OverrideFont); -} - - -//! Reads attributes of the element -void StaticText::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) -{ - IGUIStaticText::deserializeAttributes(in,options); - - Border = in->getAttributeAsBool("Border"); - enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); - OverrideBGColorEnabled = in->getAttributeAsBool("OverrideBGColorEnabled"); - setWordWrap(in->getAttributeAsBool("WordWrap")); - Background = in->getAttributeAsBool("Background"); - RightToLeft = in->getAttributeAsBool("RightToLeft"); - RestrainTextInside = in->getAttributeAsBool("RestrainTextInside"); - OverrideColor = in->getAttributeAsColor("OverrideColor"); - BGColor = in->getAttributeAsColor("BGColor"); - - setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), - (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); - - // OverrideFont = in->getAttributeAsFont("OverrideFont"); -} - -} // end namespace gui -} // end namespace irr - - -#endif // _IRR_COMPILE_WITH_GUI_ diff --git a/src/util/statictext.h b/src/util/statictext.h deleted file mode 100644 index 8d2f879e7..000000000 --- a/src/util/statictext.h +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (C) 2002-2012 Nikolaus Gebhardt -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#ifndef __C_GUI_STATIC_TEXT_H_INCLUDED__ -#define __C_GUI_STATIC_TEXT_H_INCLUDED__ - -#include "IrrCompileConfig.h" -#ifdef _IRR_COMPILE_WITH_GUI_ - -#include "IGUIStaticText.h" -#include "irrArray.h" - -#include - -namespace irr -{ -namespace gui -{ - class StaticText : public IGUIStaticText - { - public: - - //! constructor - StaticText(const wchar_t* text, bool border, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, const core::rect& rectangle, - bool background = false); - - //! destructor - virtual ~StaticText(); - - //! draws the element and its children - virtual void draw(); - - //! Sets another skin independent font. - virtual void setOverrideFont(IGUIFont* font=0); - - //! Gets the override font (if any) - virtual IGUIFont* getOverrideFont() const; - - //! Get the font which is used right now for drawing - virtual IGUIFont* getActiveFont() const; - - //! Sets another color for the text. - virtual void setOverrideColor(video::SColor color); - - //! Sets another color for the background. - virtual void setBackgroundColor(video::SColor color); - - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw); - - //! Gets the background color - virtual video::SColor getBackgroundColor() const; - - //! Checks if background drawing is enabled - virtual bool isDrawBackgroundEnabled() const; - - //! Sets whether to draw the border - virtual void setDrawBorder(bool draw); - - //! Checks if border drawing is enabled - virtual bool isDrawBorderEnabled() const; - - //! Sets alignment mode for text - virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); - - //! Gets the override color - #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 - virtual const video::SColor& getOverrideColor() const; - #else - virtual video::SColor getOverrideColor() const; - #endif - - //! Sets if the static text should use the overide color or the - //! color in the gui skin. - virtual void enableOverrideColor(bool enable); - - //! Checks if an override color is enabled - virtual bool isOverrideColorEnabled() const; - - //! Set whether the text in this label should be clipped if it goes outside bounds - virtual void setTextRestrainedInside(bool restrainedInside); - - //! Checks if the text in this label should be clipped if it goes outside bounds - virtual bool isTextRestrainedInside() const; - - //! Enables or disables word wrap for using the static text as - //! multiline text control. - virtual void setWordWrap(bool enable); - - //! Checks if word wrap is enabled - virtual bool isWordWrapEnabled() const; - - //! Sets the new caption of this element. - virtual void setText(const wchar_t* text); - - //! Returns the height of the text in pixels when it is drawn. - virtual s32 getTextHeight() const; - - //! Returns the width of the current text, in the current font - virtual s32 getTextWidth() const; - - //! Updates the absolute position, splits text if word wrap is enabled - virtual void updateAbsolutePosition(); - - //! Set whether the string should be interpreted as right-to-left (RTL) text - /** \note This component does not implement the Unicode bidi standard, the - text of the component should be already RTL if you call this. The - main difference when RTL is enabled is that the linebreaks for multiline - elements are performed starting from the end. - */ - virtual void setRightToLeft(bool rtl); - - //! Checks if the text should be interpreted as right-to-left text - virtual bool isRightToLeft() const; - - //! Writes attributes of the element. - virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; - - //! Reads attributes of the element - virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); - - private: - - //! Breaks the single text line. - void breakText(); - - EGUI_ALIGNMENT HAlign, VAlign; - bool Border; - bool OverrideColorEnabled; - bool OverrideBGColorEnabled; - bool WordWrap; - bool Background; - bool RestrainTextInside; - bool RightToLeft; - - video::SColor OverrideColor, BGColor; - gui::IGUIFont* OverrideFont; - gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated. - - core::array< core::stringw > BrokenText; - }; - -} // end namespace gui -} // end namespace irr - -#endif // _IRR_COMPILE_WITH_GUI_ - -#endif // C_GUI_STATIC_TEXT_H_INCLUDED diff --git a/src/util/string.h b/src/util/string.h index 40ef3e4d3..c77c5a6f9 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -519,6 +519,38 @@ std::basic_string unescape_enriched(const std::basic_string &s) return output; } +template +std::vector > split(const std::basic_string &s, T delim) +{ + std::vector > tokens; + + std::basic_string current; + bool last_was_escape = false; + for (size_t i = 0; i < s.length(); i++) { + T si = s[i]; + if (last_was_escape) { + current += '\\'; + current += si; + last_was_escape = false; + } else { + if (si == delim) { + tokens.push_back(current); + current = std::basic_string(); + last_was_escape = false; + } else if (si == '\\') { + last_was_escape = true; + } else { + current += si; + last_was_escape = false; + } + } + } + //push last element + tokens.push_back(current); + + return tokens; +} + /** * Checks that all characters in \p to_check are a decimal digits. * -- cgit v1.2.3 From 27aff22a9b68044d3ea51db731597834336effa3 Mon Sep 17 00:00:00 2001 From: kwolekr Date: Sat, 11 Jun 2016 03:23:53 -0400 Subject: Random misc. warning fixes and cleanups - Fix unused c_sand member warning in Valleys Mapgen - Fix some code style - Make some std::string params const ref --- src/mapgen_valleys.h | 1 - src/util/string.cpp | 19 +++++++++++-------- src/util/string.h | 4 ++-- 3 files changed, 13 insertions(+), 11 deletions(-) (limited to 'src/util') diff --git a/src/mapgen_valleys.h b/src/mapgen_valleys.h index a7369ea92..faaffa905 100644 --- a/src/mapgen_valleys.h +++ b/src/mapgen_valleys.h @@ -125,7 +125,6 @@ private: Noise *noise_valley_profile; content_t c_lava_source; - content_t c_sand; float terrainLevelAtPoint(s16 x, s16 z); diff --git a/src/util/string.cpp b/src/util/string.cpp index 2c4143c76..94064ef93 100644 --- a/src/util/string.cpp +++ b/src/util/string.cpp @@ -314,7 +314,7 @@ std::string wide_to_narrow(const std::wstring &wcs) #endif -std::string urlencode(std::string str) +std::string urlencode(const std::string &str) { // Encodes non-unreserved URI characters by a percent sign // followed by two hex digits. See RFC 3986, section 2.3. @@ -322,17 +322,18 @@ std::string urlencode(std::string str) std::ostringstream oss(std::ios::binary); for (u32 i = 0; i < str.size(); i++) { unsigned char c = str[i]; - if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') + if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') { oss << c; - else + } else { oss << "%" << url_hex_chars[(c & 0xf0) >> 4] << url_hex_chars[c & 0x0f]; + } } return oss.str(); } -std::string urldecode(std::string str) +std::string urldecode(const std::string &str) { // Inverse of urlencode std::ostringstream oss(std::ios::binary); @@ -343,18 +344,20 @@ std::string urldecode(std::string str) hex_digit_decode(str[i+2], lowvalue)) { oss << (char) ((highvalue << 4) | lowvalue); i += 2; - } - else + } else { oss << str[i]; + } } return oss.str(); } u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask) { - u32 result = 0, mask = 0; + u32 result = 0; + u32 mask = 0; char *s = &str[0]; - char *flagstr, *strpos = NULL; + char *flagstr; + char *strpos = NULL; while ((flagstr = strtok_r(s, ",", &strpos))) { s = NULL; diff --git a/src/util/string.h b/src/util/string.h index c77c5a6f9..8f4ef4711 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -77,8 +77,8 @@ wchar_t *narrow_to_wide_c(const char *str); std::wstring narrow_to_wide(const std::string &mbs); std::string wide_to_narrow(const std::wstring &wcs); -std::string urlencode(std::string str); -std::string urldecode(std::string str); +std::string urlencode(const std::string &str); +std::string urldecode(const std::string &str); u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask); std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask); size_t mystrlcpy(char *dst, const char *src, size_t size); -- cgit v1.2.3 From 058a869b70072aba8baea47e359c45e82daaf152 Mon Sep 17 00:00:00 2001 From: Ner'zhul Date: Wed, 10 Aug 2016 12:08:05 +0200 Subject: Permit usage of std::unordered_map & std::unorderered_set on c++11 compilers (#4430) This fallback to std::map & std::set for older compilers Use UNORDERED_SET as an example in decoration and ore biome sets Use UNORDERED_MAP as an example in nameidmapping --- src/mg_decoration.cpp | 2 +- src/mg_decoration.h | 4 ++-- src/mg_ore.cpp | 10 +++++----- src/mg_ore.h | 3 ++- src/nameidmapping.cpp | 2 +- src/nameidmapping.h | 12 ++++++------ src/script/lua_api/l_mapgen.cpp | 4 ++-- src/util/cpp11_container.h | 35 +++++++++++++++++++++++++++++++++++ 8 files changed, 54 insertions(+), 18 deletions(-) create mode 100644 src/util/cpp11_container.h (limited to 'src/util') diff --git a/src/mg_decoration.cpp b/src/mg_decoration.cpp index 70dd9817a..127915b51 100644 --- a/src/mg_decoration.cpp +++ b/src/mg_decoration.cpp @@ -156,7 +156,7 @@ size_t Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) } if (mg->biomemap) { - std::set::iterator iter; + UNORDERED_SET::iterator iter; if (!biomes.empty()) { iter = biomes.find(mg->biomemap[mapindex]); diff --git a/src/mg_decoration.h b/src/mg_decoration.h index ba3e9d3b2..da98fd482 100644 --- a/src/mg_decoration.h +++ b/src/mg_decoration.h @@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef MG_DECORATION_HEADER #define MG_DECORATION_HEADER -#include +#include "util/cpp11_container.h" #include "objdef.h" #include "noise.h" #include "nodedef.h" @@ -83,7 +83,7 @@ public: float fill_ratio; NoiseParams np; - std::set biomes; + UNORDERED_SET biomes; //std::list cutoffs; //Mutex cutoff_mutex; }; diff --git a/src/mg_ore.cpp b/src/mg_ore.cpp index 257901614..d840d745a 100644 --- a/src/mg_ore.cpp +++ b/src/mg_ore.cpp @@ -148,7 +148,7 @@ void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, if (biomemap && !biomes.empty()) { u32 index = sizex * (z0 - nmin.Z) + (x0 - nmin.X); - std::set::iterator it = biomes.find(biomemap[index]); + UNORDERED_SET::iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } @@ -202,7 +202,7 @@ void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, continue; if (biomemap && !biomes.empty()) { - std::set::iterator it = biomes.find(biomemap[index]); + UNORDERED_SET::iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } @@ -270,7 +270,7 @@ void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed, continue; if (biomemap && !biomes.empty()) { - std::set::iterator it = biomes.find(biomemap[index]); + UNORDERED_SET::iterator it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } @@ -338,7 +338,7 @@ void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, if (biomemap && !biomes.empty()) { u32 bmapidx = sizex * (z0 - nmin.Z) + (x0 - nmin.X); - std::set::iterator it = biomes.find(biomemap[bmapidx]); + UNORDERED_SET::iterator it = biomes.find(biomemap[bmapidx]); if (it == biomes.end()) continue; } @@ -422,7 +422,7 @@ void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, if (biomemap && !biomes.empty()) { u32 bmapidx = sizex * (z - nmin.Z) + (x - nmin.X); - std::set::iterator it = biomes.find(biomemap[bmapidx]); + UNORDERED_SET::iterator it = biomes.find(biomemap[bmapidx]); if (it == biomes.end()) continue; } diff --git a/src/mg_ore.h b/src/mg_ore.h index 2e065cee3..e95fdd330 100644 --- a/src/mg_ore.h +++ b/src/mg_ore.h @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef MG_ORE_HEADER #define MG_ORE_HEADER +#include "util/cpp11_container.h" #include "objdef.h" #include "noise.h" #include "nodedef.h" @@ -64,7 +65,7 @@ public: float nthresh; // threshold for noise at which an ore is placed NoiseParams np; // noise for distribution of clusters (NULL for uniform scattering) Noise *noise; - std::set biomes; + UNORDERED_SET biomes; Ore(); virtual ~Ore(); diff --git a/src/nameidmapping.cpp b/src/nameidmapping.cpp index ed59ddd16..2af8befff 100644 --- a/src/nameidmapping.cpp +++ b/src/nameidmapping.cpp @@ -25,7 +25,7 @@ void NameIdMapping::serialize(std::ostream &os) const { writeU8(os, 0); // version writeU16(os, m_id_to_name.size()); - for(std::map::const_iterator + for(UNORDERED_MAP::const_iterator i = m_id_to_name.begin(); i != m_id_to_name.end(); ++i){ writeU16(os, i->first); diff --git a/src/nameidmapping.h b/src/nameidmapping.h index 417c441d2..23838c8ff 100644 --- a/src/nameidmapping.h +++ b/src/nameidmapping.h @@ -23,15 +23,15 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include -#include #include "irrlichttypes_bloated.h" +#include "util/cpp11_container.h" class NameIdMapping { public: void serialize(std::ostream &os) const; void deSerialize(std::istream &is); - + void clear(){ m_id_to_name.clear(); m_name_to_id.clear(); @@ -55,7 +55,7 @@ public: m_name_to_id.erase(name); } bool getName(u16 id, std::string &result) const{ - std::map::const_iterator i; + UNORDERED_MAP::const_iterator i; i = m_id_to_name.find(id); if(i == m_id_to_name.end()) return false; @@ -63,7 +63,7 @@ public: return true; } bool getId(const std::string &name, u16 &result) const{ - std::map::const_iterator i; + UNORDERED_MAP::const_iterator i; i = m_name_to_id.find(name); if(i == m_name_to_id.end()) return false; @@ -74,8 +74,8 @@ public: return m_id_to_name.size(); } private: - std::map m_id_to_name; - std::map m_name_to_id; + UNORDERED_MAP m_id_to_name; + UNORDERED_MAP m_name_to_id; }; #endif diff --git a/src/script/lua_api/l_mapgen.cpp b/src/script/lua_api/l_mapgen.cpp index 9f14838ce..9f28231eb 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -100,7 +100,7 @@ Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr); Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef); size_t get_biome_list(lua_State *L, int index, - BiomeManager *biomemgr, std::set *biome_id_list); + BiomeManager *biomemgr, UNORDERED_SET *biome_id_list); Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names); @@ -401,7 +401,7 @@ Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef) size_t get_biome_list(lua_State *L, int index, - BiomeManager *biomemgr, std::set *biome_id_list) + BiomeManager *biomemgr, UNORDERED_SET *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; diff --git a/src/util/cpp11_container.h b/src/util/cpp11_container.h new file mode 100644 index 000000000..f839be19a --- /dev/null +++ b/src/util/cpp11_container.h @@ -0,0 +1,35 @@ +/* +Minetest +Copyright (C) 2016 nerzhul, Loic Blot + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MT_CPP11CONTAINER_HEADER +#define MT_CPP11CONTAINER_HEADER + +#if __cplusplus >= 201103L + #include + #include + #define UNORDERED_MAP std::unordered_map + #define UNORDERED_SET std::unordered_set +#else + #include + #include + #define UNORDERED_MAP std::map + #define UNORDERED_SET std::set +#endif + +#endif -- cgit v1.2.3 From 48b3bb980d4a026d32739acc1982f16e3c303c5b Mon Sep 17 00:00:00 2001 From: David Carlier Date: Thu, 28 Jul 2016 08:56:22 +0100 Subject: couple of memory leaks fixes. --- src/script/cpp_api/s_security.cpp | 18 +++++++++++++++++- src/sound_openal.cpp | 1 + src/unittest/test_map_settings_manager.cpp | 4 +++- src/util/areastore.cpp | 1 + src/util/srp.cpp | 2 +- 5 files changed, 23 insertions(+), 3 deletions(-) (limited to 'src/util') diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index e117a4811..0e64c4c61 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -285,6 +285,10 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path) if (c == LUA_SIGNATURE[0]) { lua_pushliteral(L, "Bytecode prohibited when mod security is enabled."); + std::fclose(fp); + if (path) { + delete [] chunk_name; + } return false; } @@ -295,7 +299,15 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path) size_t size = std::ftell(fp) - start; char *code = new char[size]; ret = std::fseek(fp, start, SEEK_SET); - CHECK_FILE_ERR(ret, fp); + if (ret) { + lua_pushfstring(L, "%s: %s", path, strerror(errno)); + std::fclose(fp); + delete [] code; + if (path) { + delete [] chunk_name; + } + return false; + } size_t num_read = std::fread(code, 1, size, fp); if (path) { @@ -303,6 +315,10 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path) } if (num_read != size) { lua_pushliteral(L, "Error reading file to load."); + delete [] code; + if (path) { + delete [] chunk_name; + } return false; } diff --git a/src/sound_openal.cpp b/src/sound_openal.cpp index e2b6d937a..1832a0c77 100644 --- a/src/sound_openal.cpp +++ b/src/sound_openal.cpp @@ -144,6 +144,7 @@ SoundBuffer *load_opened_ogg_file(OggVorbis_File *oggFile, ov_clear(oggFile); infostream << "Audio: Error decoding " << filename_for_logging << std::endl; + delete snd; return NULL; } diff --git a/src/unittest/test_map_settings_manager.cpp b/src/unittest/test_map_settings_manager.cpp index 9292bf87c..4f5ac80f2 100644 --- a/src/unittest/test_map_settings_manager.cpp +++ b/src/unittest/test_map_settings_manager.cpp @@ -75,8 +75,10 @@ std::string read_file_to_string(const std::string &filepath) fseek(f, 0, SEEK_END); long filesize = ftell(f); - if (filesize == -1) + if (filesize == -1) { + fclose(f); return ""; + } rewind(f); buf.resize(filesize); diff --git a/src/util/areastore.cpp b/src/util/areastore.cpp index 58f08a8c2..cef67da2c 100644 --- a/src/util/areastore.cpp +++ b/src/util/areastore.cpp @@ -95,6 +95,7 @@ void AreaStore::deserialize(std::istream &is) is.read(data, data_len); a.data = std::string(data, data_len); insertArea(&a); + delete [] data; } } diff --git a/src/util/srp.cpp b/src/util/srp.cpp index 0d3c938a3..77c1816e8 100644 --- a/src/util/srp.cpp +++ b/src/util/srp.cpp @@ -542,7 +542,7 @@ static SRP_Result fill_buff() if (!fp) return SRP_ERR; - if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) return SRP_ERR; + if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) { fclose(fp); return SRP_ERR; } if (fclose(fp)) return SRP_ERR; #endif return SRP_OK; -- cgit v1.2.3 From b11720af459d44a553cb5d23ef776a632fb30a65 Mon Sep 17 00:00:00 2001 From: Rogier-5 Date: Thu, 11 Aug 2016 19:22:40 +0200 Subject: Use the standard to_string() functions for C++11 (#4279) If compiling according to a C++ version before C++11, then define std::to_string ourselves. Add a to_wstring version as well As std::to_string() for floating point types uses %.6f as floating point format converter, instead of %G, it needs special care. To preserve ftos() behavior (which is expected to use the %G format converter), it no longer uses to_string(). --- src/client.cpp | 2 +- src/util/string.h | 47 +++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 42 insertions(+), 7 deletions(-) (limited to 'src/util') diff --git a/src/client.cpp b/src/client.cpp index 4ffcec6ba..483b22caa 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -820,7 +820,7 @@ void Client::initLocalMapSaving(const Address &address, const std::string world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + "server_" - + hostname + "_" + to_string(address.getPort()); + + hostname + "_" + std::to_string(address.getPort()); fs::CreateAllDirs(world_path); diff --git a/src/util/string.h b/src/util/string.h index 8f4ef4711..724543a36 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -27,6 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include #include #define STRINGIFY(x) #x @@ -350,23 +351,57 @@ inline T from_string(const std::string &str) /// Returns a 64-bit signed value represented by the string \p str (decimal). inline s64 stoi64(const std::string &str) { return from_string(str); } -// TODO: Replace with C++11 std::to_string. +#if __cplusplus < 201103L +namespace std { /// Returns a string representing the value \p val. template -inline std::string to_string(T val) +inline string to_string(T val) { - std::ostringstream oss; + ostringstream oss; oss << val; return oss.str(); } +#define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \ + template <> \ + inline string to_string(T val) \ + { \ + ostringstream oss; \ + oss << std::fixed \ + << std::setprecision(6) \ + << val; \ + return oss.str(); \ + } +DEFINE_STD_TOSTRING_FLOATINGPOINT(float) +DEFINE_STD_TOSTRING_FLOATINGPOINT(double) +DEFINE_STD_TOSTRING_FLOATINGPOINT(long double) + +#undef DEFINE_STD_TOSTRING_FLOATINGPOINT + +/// Returns a wide string representing the value \p val +template +inline wstring to_wstring(T val) +{ + return utf8_to_wide(to_string(val)); +} +} +#endif /// Returns a string representing the decimal value of the 32-bit value \p i. -inline std::string itos(s32 i) { return to_string(i); } +inline std::string itos(s32 i) { return std::to_string(i); } /// Returns a string representing the decimal value of the 64-bit value \p i. -inline std::string i64tos(s64 i) { return to_string(i); } +inline std::string i64tos(s64 i) { return std::to_string(i); } + +// std::to_string uses the '%.6f' conversion, which is inconsistent with +// std::ostream::operator<<() and impractical too. ftos() uses the +// more generic and std::ostream::operator<<()-compatible '%G' format. /// Returns a string representing the decimal value of the float value \p f. -inline std::string ftos(float f) { return to_string(f); } +inline std::string ftos(float f) +{ + std::ostringstream oss; + oss << f; + return oss.str(); +} /** -- cgit v1.2.3 From 667975fe3adee935a3f4d2b1a421a295771c664d Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Thu, 6 Oct 2016 08:48:20 +0200 Subject: Use more unordered_maps to improve performance in c++11 builds --- src/client.cpp | 9 +++------ src/client.h | 6 +++--- src/clientobject.cpp | 10 ++++------ src/clientobject.h | 3 ++- src/content_cao.cpp | 2 +- src/network/clientpackethandler.cpp | 4 +--- src/script/lua_api/l_mapgen.cpp | 4 ++-- src/server.cpp | 8 ++++---- src/util/string.h | 3 ++- 9 files changed, 22 insertions(+), 27 deletions(-) (limited to 'src/util') diff --git a/src/client.cpp b/src/client.cpp index a599e21dc..63653998a 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -623,10 +623,8 @@ void Client::step(float dtime) Update positions of sounds attached to objects */ { - for(std::map::iterator - i = m_sounds_to_objects.begin(); - i != m_sounds_to_objects.end(); ++i) - { + for(UNORDERED_MAP::iterator i = m_sounds_to_objects.begin(); + i != m_sounds_to_objects.end(); ++i) { int client_id = i->first; u16 object_id = i->second; ClientActiveObject *cao = m_env.getActiveObject(object_id); @@ -645,8 +643,7 @@ void Client::step(float dtime) m_removed_sounds_check_timer = 0; // Find removed sounds and clear references to them std::vector removed_server_ids; - for(std::map::iterator - i = m_sounds_server_to_client.begin(); + for(UNORDERED_MAP::iterator i = m_sounds_server_to_client.begin(); i != m_sounds_server_to_client.end();) { s32 server_id = i->first; int client_id = i->second; diff --git a/src/client.h b/src/client.h index fb479068f..a71c1dcbc 100644 --- a/src/client.h +++ b/src/client.h @@ -663,11 +663,11 @@ private: // Sounds float m_removed_sounds_check_timer; // Mapping from server sound ids to our sound ids - std::map m_sounds_server_to_client; + UNORDERED_MAP m_sounds_server_to_client; // And the other way! - std::map m_sounds_client_to_server; + UNORDERED_MAP m_sounds_client_to_server; // And relations to objects - std::map m_sounds_to_objects; + UNORDERED_MAP m_sounds_to_objects; // Privileges UNORDERED_SET m_privileges; diff --git a/src/clientobject.cpp b/src/clientobject.cpp index a11757ea6..ff3f47187 100644 --- a/src/clientobject.cpp +++ b/src/clientobject.cpp @@ -43,12 +43,11 @@ ClientActiveObject* ClientActiveObject::create(ActiveObjectType type, IGameDef *gamedef, ClientEnvironment *env) { // Find factory function - std::map::iterator n; - n = m_types.find(type); + UNORDERED_MAP::iterator n = m_types.find(type); if(n == m_types.end()) { // If factory is not found, just return. - warningstream<<"ClientActiveObject: No factory for type=" - <<(int)type< +#include "util/cpp11_container.h" /* @@ -103,7 +104,7 @@ protected: ClientEnvironment *m_env; private: // Used for creating objects based on type - static std::map m_types; + static UNORDERED_MAP m_types; }; struct DistanceSortedActiveObject diff --git a/src/content_cao.cpp b/src/content_cao.cpp index a141690f6..33dae6822 100644 --- a/src/content_cao.cpp +++ b/src/content_cao.cpp @@ -51,7 +51,7 @@ struct ToolCapabilities; #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")" -std::map ClientActiveObject::m_types; +UNORDERED_MAP ClientActiveObject::m_types; SmoothTranslator::SmoothTranslator(): vect_old(0,0,0), diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 48c573da5..6d42edd7d 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -812,9 +812,7 @@ void Client::handleCommand_StopSound(NetworkPacket* pkt) *pkt >> server_id; - std::map::iterator i = - m_sounds_server_to_client.find(server_id); - + UNORDERED_MAP::iterator i = m_sounds_server_to_client.find(server_id); if (i != m_sounds_server_to_client.end()) { int client_id = i->second; m_sound->stopSound(client_id); diff --git a/src/script/lua_api/l_mapgen.cpp b/src/script/lua_api/l_mapgen.cpp index a176f4f52..da8e71cdc 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -244,7 +244,7 @@ bool read_schematic_def(lua_State *L, int index, schem->schemdata = new MapNode[numnodes]; size_t names_base = names->size(); - std::map name_id_map; + UNORDERED_MAP name_id_map; u32 i = 0; for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) { @@ -266,7 +266,7 @@ bool read_schematic_def(lua_State *L, int index, u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping - std::map::iterator it = name_id_map.find(name); + UNORDERED_MAP::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; diff --git a/src/server.cpp b/src/server.cpp index a8494f76e..e9983ba11 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -794,7 +794,7 @@ void Server::AsyncRunStep(bool initial_step) // Key = object id // Value = data sent by object - std::map* > buffered_messages; + UNORDERED_MAP* > buffered_messages; // Get active object messages from environment for(;;) { @@ -803,7 +803,7 @@ void Server::AsyncRunStep(bool initial_step) break; std::vector* message_list = NULL; - std::map* >::iterator n; + UNORDERED_MAP* >::iterator n; n = buffered_messages.find(aom.id); if (n == buffered_messages.end()) { message_list = new std::vector; @@ -824,7 +824,7 @@ void Server::AsyncRunStep(bool initial_step) std::string reliable_data; std::string unreliable_data; // Go through all objects in message buffer - for (std::map* >::iterator + for (UNORDERED_MAP* >::iterator j = buffered_messages.begin(); j != buffered_messages.end(); ++j) { // If object is not known by client, skip it @@ -868,7 +868,7 @@ void Server::AsyncRunStep(bool initial_step) m_clients.unlock(); // Clear buffered_messages - for(std::map* >::iterator + for(UNORDERED_MAP* >::iterator i = buffered_messages.begin(); i != buffered_messages.end(); ++i) { delete i->second; diff --git a/src/util/string.h b/src/util/string.h index 724543a36..572c37150 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #define UTIL_STRING_HEADER #include "irrlichttypes_bloated.h" +#include "cpp11_container.h" #include #include #include @@ -54,7 +55,7 @@ with this program; if not, write to the Free Software Foundation, Inc., (((unsigned char)(x) < 0xe0) ? 2 : \ (((unsigned char)(x) < 0xf0) ? 3 : 4)) -typedef std::map StringMap; +typedef UNORDERED_MAP StringMap; struct FlagDesc { const char *name; -- cgit v1.2.3 From 155288ee981c70f505526347cb2bcda4df1c8e6b Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Thu, 6 Oct 2016 19:20:12 +0200 Subject: use unordered containers where possible (patch 4 on X) Also remove some unused parameters/functions --- src/content_sao.cpp | 28 ++++++++++++++++++---------- src/content_sao.h | 5 +++-- src/guiFormSpecMenu.h | 4 +--- src/map.h | 1 + src/mapblock_mesh.cpp | 24 ++++++++++-------------- src/mapblock_mesh.h | 15 ++++++++------- src/network/serverpackethandler.cpp | 4 +--- src/script/cpp_api/s_async.cpp | 3 ++- src/script/cpp_api/s_async.h | 2 +- src/server.cpp | 21 +++++++++------------ src/server.h | 16 ++++++---------- src/util/numeric.cpp | 2 +- src/util/numeric.h | 37 ++----------------------------------- 13 files changed, 63 insertions(+), 99 deletions(-) (limited to 'src/util') diff --git a/src/content_sao.cpp b/src/content_sao.cpp index 1e7e788e9..895c26044 100644 --- a/src/content_sao.cpp +++ b/src/content_sao.cpp @@ -347,8 +347,10 @@ void LuaEntitySAO::step(float dtime, bool send_recommended) if(m_bone_position_sent == false){ m_bone_position_sent = true; - for(std::map >::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){ - std::string str = gob_cmd_update_bone_position((*ii).first, (*ii).second.X, (*ii).second.Y); + for (UNORDERED_MAP >::const_iterator + ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){ + std::string str = gob_cmd_update_bone_position((*ii).first, + (*ii).second.X, (*ii).second.Y); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); @@ -383,8 +385,10 @@ std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version) os< >::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){ - os< >::const_iterator + ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) { + os << serializeLongString(gob_cmd_update_bone_position((*ii).first, + (*ii).second.X, (*ii).second.Y)); // m_bone_position.size } os< >::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){ + for (UNORDERED_MAP >::const_iterator + ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) { os< >::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){ - std::string str = gob_cmd_update_bone_position((*ii).first, (*ii).second.X, (*ii).second.Y); + for (UNORDERED_MAP >::const_iterator + ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) { + std::string str = gob_cmd_update_bone_position((*ii).first, + (*ii).second.X, (*ii).second.Y); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } - if(m_attachment_sent == false){ + if (!m_attachment_sent){ m_attachment_sent = true; - std::string str = gob_cmd_update_attachment(m_attachment_parent_id, m_attachment_bone, m_attachment_position, m_attachment_rotation); + std::string str = gob_cmd_update_attachment(m_attachment_parent_id, + m_attachment_bone, m_attachment_position, m_attachment_rotation); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); diff --git a/src/content_sao.h b/src/content_sao.h index 44d40d332..ccae90b77 100644 --- a/src/content_sao.h +++ b/src/content_sao.h @@ -112,7 +112,7 @@ private: bool m_animation_loop; bool m_animation_sent; - std::map > m_bone_position; + UNORDERED_MAP > m_bone_position; bool m_bone_position_sent; int m_attachment_parent_id; @@ -321,7 +321,8 @@ private: bool m_animation_loop; bool m_animation_sent; - std::map > m_bone_position; // Stores position and rotation for each bone name + // Stores position and rotation for each bone name + UNORDERED_MAP > m_bone_position; bool m_bone_position_sent; int m_attachment_parent_id; diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 21054b725..153720975 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -409,8 +409,6 @@ protected: std::vector > > m_dropdowns; ItemSpec *m_selected_item; - f32 m_timer1; - f32 m_timer2; u32 m_selected_amount; bool m_selected_dragging; @@ -462,7 +460,7 @@ private: GUITable::TableOptions table_options; GUITable::TableColumns table_columns; // used to restore table selection/scroll/treeview state - std::map table_dyndata; + UNORDERED_MAP table_dyndata; } parserData; typedef struct { diff --git a/src/map.h b/src/map.h index 13775fde1..c73fa92bf 100644 --- a/src/map.h +++ b/src/map.h @@ -32,6 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "voxel.h" #include "modifiedstate.h" #include "util/container.h" +#include "util/cpp11_container.h" #include "nodetimer.h" #include "map_settings_manager.h" diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index a11fb5887..00f83e7ab 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -1033,7 +1033,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_enable_shaders = data->m_use_shaders; m_use_tangent_vertices = data->m_use_tangent_vertices; m_enable_vbo = g_settings->getBool("enable_vbo"); - + if (g_settings->getBool("enable_minimap")) { m_minimap_mapblock = new MinimapMapblock; m_minimap_mapblock->getMinimapNodes( @@ -1298,10 +1298,8 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat // Cracks if(crack != m_last_crack) { - for(std::map::iterator - i = m_crack_materials.begin(); - i != m_crack_materials.end(); ++i) - { + for (UNORDERED_MAP::iterator i = m_crack_materials.begin(); + i != m_crack_materials.end(); ++i) { scene::IMeshBuffer *buf = m_mesh->getMeshBuffer(i->first); std::string basename = i->second; @@ -1315,9 +1313,9 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat // If the current material is also animated, // update animation info - std::map::iterator anim_iter = - m_animation_tiles.find(i->first); - if(anim_iter != m_animation_tiles.end()){ + UNORDERED_MAP::iterator anim_iter = + m_animation_tiles.find(i->first); + if (anim_iter != m_animation_tiles.end()){ TileSpec &tile = anim_iter->second; tile.texture = new_texture; tile.texture_id = new_texture_id; @@ -1330,10 +1328,8 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat } // Texture animation - for(std::map::iterator - i = m_animation_tiles.begin(); - i != m_animation_tiles.end(); ++i) - { + for (UNORDERED_MAP::iterator i = m_animation_tiles.begin(); + i != m_animation_tiles.end(); ++i) { const TileSpec &tile = i->second; // Figure out current frame int frameoffset = m_animation_frame_offsets[i->first]; @@ -1443,7 +1439,7 @@ void MeshCollector::append(const TileSpec &tile, vertices[i].Color, vertices[i].TCoords); p->vertices.push_back(vert); } - } + } for (u32 i = 0; i < numIndices; i++) { u32 j = indices[i] + vertex_count; @@ -1499,7 +1495,7 @@ void MeshCollector::append(const TileSpec &tile, vertices[i].Normal, c, vertices[i].TCoords); p->vertices.push_back(vert); } - } + } for (u32 i = 0; i < numIndices; i++) { u32 j = indices[i] + vertex_count; diff --git a/src/mapblock_mesh.h b/src/mapblock_mesh.h index f89fbe669..8376468da 100644 --- a/src/mapblock_mesh.h +++ b/src/mapblock_mesh.h @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irrlichttypes_extrabloated.h" #include "client/tile.h" #include "voxel.h" +#include "util/cpp11_container.h" #include class IGameDef; @@ -121,7 +122,7 @@ public: if(m_animation_force_timer > 0) m_animation_force_timer--; } - + void updateCameraOffset(v3s16 camera_offset); private: @@ -144,20 +145,20 @@ private: // Last crack value passed to animate() int m_last_crack; // Maps mesh buffer (i.e. material) indices to base texture names - std::map m_crack_materials; + UNORDERED_MAP m_crack_materials; // Animation info: texture animationi // Maps meshbuffers to TileSpecs - std::map m_animation_tiles; - std::map m_animation_frames; // last animation frame - std::map m_animation_frame_offsets; - + UNORDERED_MAP m_animation_tiles; + UNORDERED_MAP m_animation_frames; // last animation frame + UNORDERED_MAP m_animation_frame_offsets; + // Animation info: day/night transitions // Last daynight_ratio value passed to animate() u32 m_last_daynight_ratio; // For each meshbuffer, maps vertex indices to (day,night) pairs std::map > > m_daynight_diffs; - + // Camera offset info -> do we have to translate the mesh? v3s16 m_camera_offset; }; diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index a8bfd9068..f9061cc4f 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -1693,9 +1693,7 @@ void Server::handleCommand_RemovedSounds(NetworkPacket* pkt) *pkt >> id; - std::map::iterator i = - m_playing_sounds.find(id); - + UNORDERED_MAP::iterator i = m_playing_sounds.find(id); if (i == m_playing_sounds.end()) continue; diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index 9bf3fcf49..1fb84fab6 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -81,6 +81,7 @@ bool AsyncEngine::registerFunction(const char* name, lua_CFunction func) if (initDone) { return false; } + functionList[name] = func; return true; } @@ -203,7 +204,7 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) { /******************************************************************************/ void AsyncEngine::prepareEnvironment(lua_State* L, int top) { - for (std::map::iterator it = functionList.begin(); + for (UNORDERED_MAP::iterator it = functionList.begin(); it != functionList.end(); it++) { lua_pushstring(L, it->first.c_str()); lua_pushcfunction(L, it->second); diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index 8d612d58c..016381e5f 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -132,7 +132,7 @@ private: bool initDone; // Internal store for registred functions - std::map functionList; + UNORDERED_MAP functionList; // Internal counter to create job IDs unsigned int jobIdCounter; diff --git a/src/server.cpp b/src/server.cpp index 639e6462a..2dd070b1a 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -868,7 +868,7 @@ void Server::AsyncRunStep(bool initial_step) m_clients.unlock(); // Clear buffered_messages - for(UNORDERED_MAP* >::iterator + for (UNORDERED_MAP* >::iterator i = buffered_messages.begin(); i != buffered_messages.end(); ++i) { delete i->second; @@ -2016,16 +2016,15 @@ s32 Server::playSound(const SimpleSoundSpec &spec, void Server::stopSound(s32 handle) { // Get sound reference - std::map::iterator i = - m_playing_sounds.find(handle); - if(i == m_playing_sounds.end()) + UNORDERED_MAP::iterator i = m_playing_sounds.find(handle); + if (i == m_playing_sounds.end()) return; ServerPlayingSound &psound = i->second; NetworkPacket pkt(TOCLIENT_STOP_SOUND, 4); pkt << handle; - for(std::set::iterator i = psound.clients.begin(); + for (UNORDERED_SET::iterator i = psound.clients.begin(); i != psound.clients.end(); ++i) { // Send as reliable m_clients.send(*i, 0, &pkt, true); @@ -2322,7 +2321,7 @@ void Server::sendMediaAnnouncement(u16 peer_id) NetworkPacket pkt(TOCLIENT_ANNOUNCE_MEDIA, 0, peer_id); pkt << (u16) m_media.size(); - for (std::map::iterator i = m_media.begin(); + for (UNORDERED_MAP::iterator i = m_media.begin(); i != m_media.end(); ++i) { pkt << i->first << i->second.sha1_digest; } @@ -2367,7 +2366,7 @@ void Server::sendRequestedMedia(u16 peer_id, i != tosend.end(); ++i) { const std::string &name = *i; - if(m_media.find(name) == m_media.end()) { + if (m_media.find(name) == m_media.end()) { errorstream<<"Server::sendRequestedMedia(): Client asked for " <<"unknown file \""<<(name)<<"\""<::iterator - i = m_playing_sounds.begin(); - i != m_playing_sounds.end();) - { + for (UNORDERED_MAP::iterator + i = m_playing_sounds.begin(); i != m_playing_sounds.end();) { ServerPlayingSound &psound = i->second; psound.clients.erase(peer_id); - if(psound.clients.empty()) + if (psound.clients.empty()) m_playing_sounds.erase(i++); else ++i; diff --git a/src/server.h b/src/server.h index 3ad894b38..34427a71a 100644 --- a/src/server.h +++ b/src/server.h @@ -157,7 +157,7 @@ struct ServerSoundParams struct ServerPlayingSound { ServerSoundParams params; - std::set clients; // peer ids + UNORDERED_SET clients; // peer ids }; class Server : public con::PeerHandler, public MapEventReceiver, @@ -243,11 +243,9 @@ public: std::wstring getStatusString(); // read shutdown state - inline bool getShutdownRequested() - { return m_shutdown_requested; } + inline bool getShutdownRequested() const { return m_shutdown_requested; } // request server to shutdown - inline void requestShutdown() { m_shutdown_requested = true; } void requestShutdown(const std::string &msg, bool reconnect) { m_shutdown_requested = true; @@ -323,8 +321,7 @@ public: const ModSpec* getModSpec(const std::string &modname) const; void getModNames(std::vector &modlist); std::string getBuiltinLuaPath(); - inline std::string getWorldPath() const - { return m_path_world; } + inline std::string getWorldPath() const { return m_path_world; } inline bool isSingleplayer() { return m_simple_singleplayer_mode; } @@ -356,8 +353,7 @@ public: bool setSky(Player *player, const video::SColor &bgcolor, const std::string &type, const std::vector ¶ms); - bool overrideDayNightRatio(Player *player, bool do_override, - float brightness); + bool overrideDayNightRatio(Player *player, bool do_override, float brightness); /* con::PeerHandler implementation. */ void peerAdded(con::Peer *peer); @@ -654,12 +650,12 @@ private: u16 m_ignore_map_edit_events_peer_id; // media files known to server - std::map m_media; + UNORDERED_MAP m_media; /* Sounds */ - std::map m_playing_sounds; + UNORDERED_MAP m_playing_sounds; s32 m_next_sound_id; /* diff --git a/src/util/numeric.cpp b/src/util/numeric.cpp index 42ebd9022..6a7bfcac9 100644 --- a/src/util/numeric.cpp +++ b/src/util/numeric.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -std::map > FacePositionCache::m_cache; +UNORDERED_MAP > FacePositionCache::m_cache; Mutex FacePositionCache::m_cache_mutex; // Calculate the borders of a "d-radius" cube // TODO: Make it work without mutex and data races, probably thread-local diff --git a/src/util/numeric.h b/src/util/numeric.h index 615327864..4cdc254c3 100644 --- a/src/util/numeric.h +++ b/src/util/numeric.h @@ -26,8 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../irr_v3d.h" #include "../irr_aabb3d.h" #include "../threading/mutex.h" +#include "cpp11_container.h" #include -#include #include @@ -41,26 +41,10 @@ public: static std::vector getFacePositions(u16 d); private: static void generateFacePosition(u16 d); - static std::map > m_cache; + static UNORDERED_MAP > m_cache; static Mutex m_cache_mutex; }; -class IndentationRaiser -{ -public: - IndentationRaiser(u16 *indentation) - { - m_indentation = indentation; - (*m_indentation)++; - } - ~IndentationRaiser() - { - (*m_indentation)--; - } -private: - u16 *m_indentation; -}; - inline s16 getContainerPos(s16 p, s16 d) { return (p>=0 ? p : p-d+1) / d; @@ -149,23 +133,6 @@ inline bool isInArea(v3s16 p, v3s16 d) #define rangelim(d, min, max) ((d) < (min) ? (min) : ((d)>(max)?(max):(d))) #define myfloor(x) ((x) > 0.0 ? (int)(x) : (int)(x) - 1) -inline v3s16 arealim(v3s16 p, s16 d) -{ - if(p.X < 0) - p.X = 0; - if(p.Y < 0) - p.Y = 0; - if(p.Z < 0) - p.Z = 0; - if(p.X > d-1) - p.X = d-1; - if(p.Y > d-1) - p.Y = d-1; - if(p.Z > d-1) - p.Z = d-1; - return p; -} - // The naive swap performs better than the xor version #define SWAP(t, x, y) do { \ t temp = x; \ -- cgit v1.2.3 From 3de9ae4e6054bb420bea8ad5621a0b76552a3621 Mon Sep 17 00:00:00 2001 From: gregorycu Date: Sat, 8 Oct 2016 23:58:47 +1100 Subject: Ensure std::unordered_ will be used on supported MSVC compilers --- src/util/cpp11_container.h | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src/util') diff --git a/src/util/cpp11_container.h b/src/util/cpp11_container.h index f839be19a..7ac2fc371 100644 --- a/src/util/cpp11_container.h +++ b/src/util/cpp11_container.h @@ -21,6 +21,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MT_CPP11CONTAINER_HEADER #if __cplusplus >= 201103L +#define USE_UNORDERED_CONTAINERS +#endif + +#if _MSC_VER >= 1800 +#define USE_UNORDERED_CONTAINERS +#endif + +#ifdef USE_UNORDERED_CONTAINERS #include #include #define UNORDERED_MAP std::unordered_map -- cgit v1.2.3 From 0baea8c25cb04bcbeca5ae532a00d877628f6b06 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Sat, 8 Oct 2016 16:25:34 +0200 Subject: Ensure std::unordered_ be used on MSVC 2010 too (#4600) --- src/util/cpp11_container.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/util') diff --git a/src/util/cpp11_container.h b/src/util/cpp11_container.h index 7ac2fc371..88317c9c4 100644 --- a/src/util/cpp11_container.h +++ b/src/util/cpp11_container.h @@ -24,7 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #define USE_UNORDERED_CONTAINERS #endif -#if _MSC_VER >= 1800 +#if _MSC_VER >= 1600 #define USE_UNORDERED_CONTAINERS #endif -- cgit v1.2.3 From b98f98b367f2c55d5a0bff4bafaaa183b3746403 Mon Sep 17 00:00:00 2001 From: Rogier-5 Date: Fri, 11 Nov 2016 09:30:37 +0100 Subject: Fix incorrect distance computation for visible blocks (#4765) The client would not compute the distance from the camera to to a mapblock correctly. The result was that blocks that were in view (i.e. not beyond the fog limit) would not be rendered. With the improved distance computation, a range adjustment that existed in clientiface.cpp is no longer required. --- src/clientiface.cpp | 2 +- src/util/numeric.cpp | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src/util') diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 7e75c69a4..bdc16f31c 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -175,7 +175,7 @@ void RemoteClient::GetNextBlocks ( const s16 full_d_max = g_settings->getS16("max_block_send_distance"); const s16 d_opt = g_settings->getS16("block_send_optimize_distance"); - const s16 d_blocks_in_sight = (full_d_max + 1) * BS * MAP_BLOCKSIZE; + const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE; s16 d_max = full_d_max; s16 d_max_gen = g_settings->getS16("max_block_generate_distance"); diff --git a/src/util/numeric.cpp b/src/util/numeric.cpp index 6a7bfcac9..a9e7ae584 100644 --- a/src/util/numeric.cpp +++ b/src/util/numeric.cpp @@ -188,14 +188,19 @@ u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed) } /* - blockpos: position of block in block coordinates + blockpos_b: position of block in block coordinates camera_pos: position of camera in nodes camera_dir: an unit vector pointing to camera direction range: viewing range + distance_ptr: return location for distance from the camera */ bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, f32 camera_fov, f32 range, f32 *distance_ptr) { + // Maximum radius of a block. The magic number is + // sqrt(3.0) / 2.0 in literal form. + const f32 block_max_radius = 0.866025403784 * MAP_BLOCKSIZE * BS; + v3s16 blockpos_nodes = blockpos_b * MAP_BLOCKSIZE; // Block center position @@ -209,7 +214,7 @@ bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, v3f blockpos_relative = blockpos - camera_pos; // Total distance - f32 d = blockpos_relative.getLength(); + f32 d = MYMAX(0, blockpos_relative.getLength() - block_max_radius); if(distance_ptr) *distance_ptr = d; @@ -218,13 +223,9 @@ bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, if(d > range) return false; - // Maximum radius of a block. The magic number is - // sqrt(3.0) / 2.0 in literal form. - f32 block_max_radius = 0.866025403784 * MAP_BLOCKSIZE * BS; - // If block is (nearly) touching the camera, don't // bother validating further (that is, render it anyway) - if(d < block_max_radius) + if(d == 0) return true; // Adjust camera position, for purposes of computing the angle, -- cgit v1.2.3