3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "IrrCompileConfig.h"
21 #include "guiChatConsole.h"
23 #include "client/client.h"
26 #include "client/keycode.h"
29 #include "client/tile.h"
30 #include "client/fontengine.h"
33 #include "irrlicht_changes/CGUITTFont.h"
34 #include "util/string.h"
37 inline u32 clamp_u8(s32 value)
39 return (u32) MYMIN(MYMAX(value, 0), 255);
42 inline bool isInCtrlKeys(const irr::EKEY_CODE& kc)
44 return kc == KEY_LCONTROL || kc == KEY_RCONTROL || kc == KEY_CONTROL;
47 GUIChatConsole::GUIChatConsole(
48 gui::IGUIEnvironment* env,
49 gui::IGUIElement* parent,
55 IGUIElement(gui::EGUIET_ELEMENT, env, parent, id,
56 core::rect<s32>(0,0,100,100)),
57 m_chat_backend(backend),
60 m_animate_time_old(porting::getTimeMs())
62 // load background settings
63 s32 console_alpha = g_settings->getS32("console_alpha");
64 m_background_color.setAlpha(clamp_u8(console_alpha));
66 // load the background texture depending on settings
67 ITextureSource *tsrc = client->getTextureSource();
68 if (tsrc->isKnownSourceImage("background_chat.jpg")) {
69 m_background = tsrc->getTexture("background_chat.jpg");
70 m_background_color.setRed(255);
71 m_background_color.setGreen(255);
72 m_background_color.setBlue(255);
74 v3f console_color = g_settings->getV3F("console_color");
75 m_background_color.setRed(clamp_u8(myround(console_color.X)));
76 m_background_color.setGreen(clamp_u8(myround(console_color.Y)));
77 m_background_color.setBlue(clamp_u8(myround(console_color.Z)));
80 const u16 chat_font_size = g_settings->getU16("chat_font_size");
81 m_font = g_fontengine->getFont(chat_font_size != 0 ?
82 rangelim(chat_font_size, 5, 72) : FONT_SIZE_UNSPECIFIED, FM_Mono);
85 errorstream << "GUIChatConsole: Unable to load mono font" << std::endl;
87 core::dimension2d<u32> dim = m_font->getDimension(L"M");
88 m_fontsize = v2u32(dim.Width, dim.Height);
91 m_fontsize.X = MYMAX(m_fontsize.X, 1);
92 m_fontsize.Y = MYMAX(m_fontsize.Y, 1);
94 // set default cursor options
95 setCursor(true, true, 2.0, 0.1);
97 // track ctrl keys for mouse event
98 m_is_ctrl_down = false;
99 m_cache_clickable_chat_weblinks = g_settings->getBool("clickable_chat_weblinks");
102 GUIChatConsole::~GUIChatConsole()
108 void GUIChatConsole::openConsole(f32 scale)
110 assert(scale > 0.0f && scale <= 1.0f);
113 m_desired_height_fraction = scale;
114 m_desired_height = scale * m_screensize.Y;
116 m_animate_time_old = porting::getTimeMs();
117 IGUIElement::setVisible(true);
118 Environment->setFocus(this);
119 m_menumgr->createdMenu(this);
122 bool GUIChatConsole::isOpen() const
127 bool GUIChatConsole::isOpenInhibited() const
129 return m_open_inhibited > 0;
132 void GUIChatConsole::closeConsole()
135 Environment->removeFocus(this);
136 m_menumgr->deletingMenu(this);
139 void GUIChatConsole::closeConsoleAtOnce()
143 recalculateConsolePosition();
146 void GUIChatConsole::replaceAndAddToHistory(const std::wstring &line)
148 ChatPrompt& prompt = m_chat_backend->getPrompt();
149 prompt.addToHistory(prompt.getLine());
150 prompt.replace(line);
154 void GUIChatConsole::setCursor(
155 bool visible, bool blinking, f32 blink_speed, f32 relative_height)
161 // leave m_cursor_blink unchanged
162 m_cursor_blink_speed = blink_speed;
166 m_cursor_blink = 0x8000; // on
167 m_cursor_blink_speed = 0.0;
172 m_cursor_blink = 0; // off
173 m_cursor_blink_speed = 0.0;
175 m_cursor_height = relative_height;
178 void GUIChatConsole::draw()
183 video::IVideoDriver* driver = Environment->getVideoDriver();
186 v2u32 screensize = driver->getScreenSize();
187 if (screensize != m_screensize)
189 // screen size has changed
190 // scale current console height to new window size
191 if (m_screensize.Y != 0)
192 m_height = m_height * screensize.Y / m_screensize.Y;
193 m_screensize = screensize;
194 m_desired_height = m_desired_height_fraction * m_screensize.Y;
199 u64 now = porting::getTimeMs();
200 animate(now - m_animate_time_old);
201 m_animate_time_old = now;
203 // Draw console elements if visible
211 gui::IGUIElement::draw();
214 void GUIChatConsole::reformatConsole()
216 s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better)
217 s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt
218 if (cols <= 0 || rows <= 0)
220 recalculateConsolePosition();
221 m_chat_backend->reformat(cols, rows);
224 void GUIChatConsole::recalculateConsolePosition()
226 core::rect<s32> rect(0, 0, m_screensize.X, m_height);
228 recalculateAbsolutePosition(false);
231 void GUIChatConsole::animate(u32 msec)
233 // animate the console height
234 s32 goal = m_open ? m_desired_height : 0;
236 // Set invisible if close animation finished (reset by openConsole)
237 // This function (animate()) is never called once its visibility becomes false so do not
238 // actually set visible to false before the inhibited period is over
239 if (!m_open && m_height == 0 && m_open_inhibited == 0)
240 IGUIElement::setVisible(false);
242 if (m_height != goal)
244 s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0);
251 if (m_height + max_change < goal)
252 m_height += max_change;
259 if (m_height > goal + max_change)
260 m_height -= max_change;
265 recalculateConsolePosition();
269 if (m_cursor_blink_speed != 0.0)
271 u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0);
272 if (blink_increase == 0)
274 m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff);
277 // decrease open inhibit counter
278 if (m_open_inhibited > msec)
279 m_open_inhibited -= msec;
281 m_open_inhibited = 0;
284 void GUIChatConsole::drawBackground()
286 video::IVideoDriver* driver = Environment->getVideoDriver();
287 if (m_background != NULL)
289 core::rect<s32> sourcerect(0, -m_height, m_screensize.X, 0);
294 &AbsoluteClippingRect,
300 driver->draw2DRectangle(
302 core::rect<s32>(0, 0, m_screensize.X, m_height),
303 &AbsoluteClippingRect);
307 void GUIChatConsole::drawText()
312 ChatBuffer& buf = m_chat_backend->getConsoleBuffer();
313 for (u32 row = 0; row < buf.getRows(); ++row)
315 const ChatFormattedLine& line = buf.getFormattedLine(row);
316 if (line.fragments.empty())
319 s32 line_height = m_fontsize.Y;
320 s32 y = row * line_height + m_height - m_desired_height;
321 if (y + line_height < 0)
324 for (const ChatFormattedFragment &fragment : line.fragments) {
325 s32 x = (fragment.column + 1) * m_fontsize.X;
326 core::rect<s32> destrect(
327 x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y);
329 if (m_font->getType() == irr::gui::EGFT_CUSTOM) {
330 // Draw colored text if possible
331 gui::CGUITTFont *tmp = static_cast<gui::CGUITTFont*>(m_font);
337 &AbsoluteClippingRect);
339 // Otherwise use standard text
341 fragment.text.c_str(),
343 video::SColor(255, 255, 255, 255),
346 &AbsoluteClippingRect);
352 void GUIChatConsole::drawPrompt()
357 ChatPrompt& prompt = m_chat_backend->getPrompt();
358 std::wstring prompt_text = prompt.getVisiblePortion();
360 u32 font_width = m_fontsize.X;
361 u32 font_height = m_fontsize.Y;
363 core::dimension2d<u32> size = m_font->getDimension(prompt_text.c_str());
364 u32 text_width = size.Width;
365 if (size.Height > font_height)
366 font_height = size.Height;
368 u32 row = m_chat_backend->getConsoleBuffer().getRows();
369 s32 y = row * font_height + m_height - m_desired_height;
371 core::rect<s32> destrect(
372 font_width, y, font_width + text_width, y + font_height);
376 video::SColor(255, 255, 255, 255),
379 &AbsoluteClippingRect);
381 // Draw the cursor during on periods
382 if ((m_cursor_blink & 0x8000) != 0)
384 s32 cursor_pos = prompt.getVisibleCursorPosition();
389 u32 text_to_cursor_pos_width = m_font->getDimension(prompt_text.substr(0, cursor_pos).c_str()).Width;
391 s32 cursor_len = prompt.getCursorLength();
392 video::IVideoDriver* driver = Environment->getVideoDriver();
393 s32 x = font_width + text_to_cursor_pos_width;
394 core::rect<s32> destrect(
396 y + font_height * (1.0 - m_cursor_height),
397 x + font_width * MYMAX(cursor_len, 1),
398 y + font_height * (cursor_len ? m_cursor_height+1 : 1)
400 video::SColor cursor_color(255,255,255,255);
401 driver->draw2DRectangle(
404 &AbsoluteClippingRect);
410 bool GUIChatConsole::OnEvent(const SEvent& event)
413 ChatPrompt &prompt = m_chat_backend->getPrompt();
415 if (event.EventType == EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)
418 if (isInCtrlKeys(event.KeyInput.Key))
420 m_is_ctrl_down = false;
423 else if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown)
426 if (isInCtrlKeys(event.KeyInput.Key)) {
427 m_is_ctrl_down = true;
431 if (KeyPress(event.KeyInput) == getKeySetting("keymap_console")) {
434 // inhibit open so the_game doesn't reopen immediately
435 m_open_inhibited = 50;
436 m_close_on_enter = false;
440 // Mac OS sends private use characters along with some keys.
441 bool has_char = event.KeyInput.Char && !event.KeyInput.Control &&
442 !iswcntrl(event.KeyInput.Char) && !IS_PRIVATE_USE_CHAR(event.KeyInput.Char);
444 if (event.KeyInput.Key == KEY_ESCAPE) {
445 closeConsoleAtOnce();
446 m_close_on_enter = false;
447 // inhibit open so the_game doesn't reopen immediately
448 m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu"
451 else if(event.KeyInput.Key == KEY_PRIOR)
453 if (!has_char) { // no num lock
454 m_chat_backend->scrollPageUp();
458 else if(event.KeyInput.Key == KEY_NEXT)
460 if (!has_char) { // no num lock
461 m_chat_backend->scrollPageDown();
465 else if(event.KeyInput.Key == KEY_RETURN)
467 prompt.addToHistory(prompt.getLine());
468 std::wstring text = prompt.replace(L"");
469 m_client->typeChatMessage(text);
470 if (m_close_on_enter) {
471 closeConsoleAtOnce();
472 m_close_on_enter = false;
476 else if(event.KeyInput.Key == KEY_UP)
478 if (!has_char) { // no num lock
480 // Move back in history
481 prompt.historyPrev();
485 else if(event.KeyInput.Key == KEY_DOWN)
487 if (!has_char) { // no num lock
489 // Move forward in history
490 prompt.historyNext();
494 else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT)
496 if (!has_char) { // no num lock
497 // Left/right pressed
498 // Move/select character/word to the left depending on control and shift keys
499 ChatPrompt::CursorOp op = event.KeyInput.Shift ?
500 ChatPrompt::CURSOROP_SELECT :
501 ChatPrompt::CURSOROP_MOVE;
502 ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ?
503 ChatPrompt::CURSOROP_DIR_LEFT :
504 ChatPrompt::CURSOROP_DIR_RIGHT;
505 ChatPrompt::CursorOpScope scope = event.KeyInput.Control ?
506 ChatPrompt::CURSOROP_SCOPE_WORD :
507 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
508 prompt.cursorOperation(op, dir, scope);
512 else if(event.KeyInput.Key == KEY_HOME)
514 if (!has_char) { // no num lock
516 // move to beginning of line
517 prompt.cursorOperation(
518 ChatPrompt::CURSOROP_MOVE,
519 ChatPrompt::CURSOROP_DIR_LEFT,
520 ChatPrompt::CURSOROP_SCOPE_LINE);
524 else if(event.KeyInput.Key == KEY_END)
526 if (!has_char) { // no num lock
528 // move to end of line
529 prompt.cursorOperation(
530 ChatPrompt::CURSOROP_MOVE,
531 ChatPrompt::CURSOROP_DIR_RIGHT,
532 ChatPrompt::CURSOROP_SCOPE_LINE);
536 else if(event.KeyInput.Key == KEY_BACK)
538 // Backspace or Ctrl-Backspace pressed
539 // delete character / word to the left
540 ChatPrompt::CursorOpScope scope =
541 event.KeyInput.Control ?
542 ChatPrompt::CURSOROP_SCOPE_WORD :
543 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
544 prompt.cursorOperation(
545 ChatPrompt::CURSOROP_DELETE,
546 ChatPrompt::CURSOROP_DIR_LEFT,
550 else if(event.KeyInput.Key == KEY_DELETE)
552 if (!has_char) { // no num lock
553 // Delete or Ctrl-Delete pressed
554 // delete character / word to the right
555 ChatPrompt::CursorOpScope scope =
556 event.KeyInput.Control ?
557 ChatPrompt::CURSOROP_SCOPE_WORD :
558 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
559 prompt.cursorOperation(
560 ChatPrompt::CURSOROP_DELETE,
561 ChatPrompt::CURSOROP_DIR_RIGHT,
566 else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control)
570 prompt.cursorOperation(
571 ChatPrompt::CURSOROP_SELECT,
572 ChatPrompt::CURSOROP_DIR_LEFT, // Ignored
573 ChatPrompt::CURSOROP_SCOPE_LINE);
576 else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control)
579 // Copy text to clipboard
580 if (prompt.getCursorLength() <= 0)
582 std::wstring wselected = prompt.getSelection();
583 std::string selected = wide_to_utf8(wselected);
584 Environment->getOSOperator()->copyToClipboard(selected.c_str());
587 else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control)
590 // paste text from clipboard
591 if (prompt.getCursorLength() > 0) {
592 // Delete selected section of text
593 prompt.cursorOperation(
594 ChatPrompt::CURSOROP_DELETE,
595 ChatPrompt::CURSOROP_DIR_LEFT, // Ignored
596 ChatPrompt::CURSOROP_SCOPE_SELECTION);
598 IOSOperator *os_operator = Environment->getOSOperator();
599 const c8 *text = os_operator->getTextFromClipboard();
602 prompt.input(utf8_to_wide(text));
605 else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control)
608 // Cut text to clipboard
609 if (prompt.getCursorLength() <= 0)
611 std::wstring wselected = prompt.getSelection();
612 std::string selected = wide_to_utf8(wselected);
613 Environment->getOSOperator()->copyToClipboard(selected.c_str());
614 prompt.cursorOperation(
615 ChatPrompt::CURSOROP_DELETE,
616 ChatPrompt::CURSOROP_DIR_LEFT, // Ignored
617 ChatPrompt::CURSOROP_SCOPE_SELECTION);
620 else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control)
623 // kill line to left end
624 prompt.cursorOperation(
625 ChatPrompt::CURSOROP_DELETE,
626 ChatPrompt::CURSOROP_DIR_LEFT,
627 ChatPrompt::CURSOROP_SCOPE_LINE);
630 else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control)
633 // kill line to right end
634 prompt.cursorOperation(
635 ChatPrompt::CURSOROP_DELETE,
636 ChatPrompt::CURSOROP_DIR_RIGHT,
637 ChatPrompt::CURSOROP_SCOPE_LINE);
640 else if(event.KeyInput.Key == KEY_TAB)
642 // Tab or Shift-Tab pressed
644 std::list<std::string> names = m_client->getConnectedPlayerNames();
645 bool backwards = event.KeyInput.Shift;
646 prompt.nickCompletion(names, backwards);
651 prompt.input(event.KeyInput.Char);
655 else if(event.EventType == EET_MOUSE_INPUT_EVENT)
657 if (event.MouseInput.Event == EMIE_MOUSE_WHEEL)
659 s32 rows = myround(-3.0 * event.MouseInput.Wheel);
660 m_chat_backend->scroll(rows);
662 // Middle click or ctrl-click opens weblink, if enabled in config
663 else if(m_cache_clickable_chat_weblinks && (
664 event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN ||
665 (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN && m_is_ctrl_down)
668 // If clicked within console output region
669 if (event.MouseInput.Y / m_fontsize.Y < (m_height / m_fontsize.Y) - 1 )
671 // Translate pixel position to font position
672 middleClick(event.MouseInput.X / m_fontsize.X, event.MouseInput.Y / m_fontsize.Y);
676 else if(event.EventType == EET_STRING_INPUT_EVENT)
678 prompt.input(std::wstring(event.StringInput.Str->c_str()));
682 return Parent ? Parent->OnEvent(event) : false;
685 void GUIChatConsole::setVisible(bool visible)
688 IGUIElement::setVisible(visible);
691 recalculateConsolePosition();
695 void GUIChatConsole::middleClick(s32 col, s32 row)
697 // Prevent accidental rapid clicking
698 static u64 s_oldtime = 0;
699 u64 newtime = porting::getTimeMs();
701 // 0.6 seconds should suffice
702 if (newtime - s_oldtime < 600)
706 const std::vector<ChatFormattedFragment> &
707 frags = m_chat_backend->getConsoleBuffer().getFormattedLine(row).fragments;
708 std::string weblink = ""; // from frag meta
710 // Identify targetted fragment, if exists
711 int indx = frags.size() - 1;
713 // Invalid row, frags is empty
716 // Scan from right to left, offset by 1 font space because left margin
717 while (indx > -1 && (u32)col < frags[indx].column + 1) {
721 weblink = frags[indx].weblink;
722 // Note if(indx < 0) then a frag somehow had a corrupt column field
726 // Debug help. Please keep this in case adjustments are made later.
728 ws = "Middleclick: (" + std::to_string(col) + ',' + std::to_string(row) + ')' + " frags:";
729 // show all frags <position>(<length>) for the clicked row
730 for (u32 i=0;i<frags.size();++i) {
732 // tag the actual clicked frag
734 ws += std::to_string(frags.at(i).column) + '('
735 + std::to_string(frags.at(i).text.size()) + "),";
737 actionstream << ws << std::endl;
741 if (weblink.size() != 0) {
742 std::ostringstream msg;
744 if (porting::open_url(weblink)) {
745 msg << gettext("Opening webpage");
748 msg << gettext("Failed to open webpage");
750 msg << " '" << weblink << "'";
751 m_chat_backend->addUnparsedMessage(utf8_to_wide(msg.str()));