Move files to subdirectories (#6599)
[oweals/minetest.git] / src / gui / guiChatConsole.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "guiChatConsole.h"
21 #include "chat.h"
22 #include "client.h"
23 #include "debug.h"
24 #include "gettime.h"
25 #include "keycode.h"
26 #include "settings.h"
27 #include "porting.h"
28 #include "client/tile.h"
29 #include "fontengine.h"
30 #include "log.h"
31 #include "gettext.h"
32 #include <string>
33
34 #if USE_FREETYPE
35         #include "irrlicht_changes/CGUITTFont.h"
36 #endif
37
38 inline u32 clamp_u8(s32 value)
39 {
40         return (u32) MYMIN(MYMAX(value, 0), 255);
41 }
42
43
44 GUIChatConsole::GUIChatConsole(
45                 gui::IGUIEnvironment* env,
46                 gui::IGUIElement* parent,
47                 s32 id,
48                 ChatBackend* backend,
49                 Client* client,
50                 IMenuManager* menumgr
51 ):
52         IGUIElement(gui::EGUIET_ELEMENT, env, parent, id,
53                         core::rect<s32>(0,0,100,100)),
54         m_chat_backend(backend),
55         m_client(client),
56         m_menumgr(menumgr),
57         m_animate_time_old(porting::getTimeMs())
58 {
59         // load background settings
60         s32 console_alpha = g_settings->getS32("console_alpha");
61         m_background_color.setAlpha(clamp_u8(console_alpha));
62
63         // load the background texture depending on settings
64         ITextureSource *tsrc = client->getTextureSource();
65         if (tsrc->isKnownSourceImage("background_chat.jpg")) {
66                 m_background = tsrc->getTexture("background_chat.jpg");
67                 m_background_color.setRed(255);
68                 m_background_color.setGreen(255);
69                 m_background_color.setBlue(255);
70         } else {
71                 v3f console_color = g_settings->getV3F("console_color");
72                 m_background_color.setRed(clamp_u8(myround(console_color.X)));
73                 m_background_color.setGreen(clamp_u8(myround(console_color.Y)));
74                 m_background_color.setBlue(clamp_u8(myround(console_color.Z)));
75         }
76
77         m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono);
78
79         if (!m_font) {
80                 errorstream << "GUIChatConsole: Unable to load mono font ";
81         } else {
82                 core::dimension2d<u32> dim = m_font->getDimension(L"M");
83                 m_fontsize = v2u32(dim.Width, dim.Height);
84                 m_font->grab();
85         }
86         m_fontsize.X = MYMAX(m_fontsize.X, 1);
87         m_fontsize.Y = MYMAX(m_fontsize.Y, 1);
88
89         // set default cursor options
90         setCursor(true, true, 2.0, 0.1);
91 }
92
93 GUIChatConsole::~GUIChatConsole()
94 {
95         if (m_font)
96                 m_font->drop();
97 }
98
99 void GUIChatConsole::openConsole(f32 scale)
100 {
101         assert(scale > 0.0f && scale <= 1.0f);
102
103         m_open = true;
104         m_desired_height_fraction = scale;
105         m_desired_height = scale * m_screensize.Y;
106         reformatConsole();
107         m_animate_time_old = porting::getTimeMs();
108         IGUIElement::setVisible(true);
109         Environment->setFocus(this);
110         m_menumgr->createdMenu(this);
111 }
112
113 bool GUIChatConsole::isOpen() const
114 {
115         return m_open;
116 }
117
118 bool GUIChatConsole::isOpenInhibited() const
119 {
120         return m_open_inhibited > 0;
121 }
122
123 void GUIChatConsole::closeConsole()
124 {
125         m_open = false;
126         Environment->removeFocus(this);
127         m_menumgr->deletingMenu(this);
128 }
129
130 void GUIChatConsole::closeConsoleAtOnce()
131 {
132         closeConsole();
133         m_height = 0;
134         recalculateConsolePosition();
135 }
136
137 f32 GUIChatConsole::getDesiredHeight() const
138 {
139         return m_desired_height_fraction;
140 }
141
142 void GUIChatConsole::replaceAndAddToHistory(std::wstring line)
143 {
144         ChatPrompt& prompt = m_chat_backend->getPrompt();
145         prompt.addToHistory(prompt.getLine());
146         prompt.replace(line);
147 }
148
149
150 void GUIChatConsole::setCursor(
151         bool visible, bool blinking, f32 blink_speed, f32 relative_height)
152 {
153         if (visible)
154         {
155                 if (blinking)
156                 {
157                         // leave m_cursor_blink unchanged
158                         m_cursor_blink_speed = blink_speed;
159                 }
160                 else
161                 {
162                         m_cursor_blink = 0x8000;  // on
163                         m_cursor_blink_speed = 0.0;
164                 }
165         }
166         else
167         {
168                 m_cursor_blink = 0;  // off
169                 m_cursor_blink_speed = 0.0;
170         }
171         m_cursor_height = relative_height;
172 }
173
174 void GUIChatConsole::draw()
175 {
176         if(!IsVisible)
177                 return;
178
179         video::IVideoDriver* driver = Environment->getVideoDriver();
180
181         // Check screen size
182         v2u32 screensize = driver->getScreenSize();
183         if (screensize != m_screensize)
184         {
185                 // screen size has changed
186                 // scale current console height to new window size
187                 if (m_screensize.Y != 0)
188                         m_height = m_height * screensize.Y / m_screensize.Y;
189                 m_screensize = screensize;
190                 m_desired_height = m_desired_height_fraction * m_screensize.Y;
191                 reformatConsole();
192         }
193
194         // Animation
195         u64 now = porting::getTimeMs();
196         animate(now - m_animate_time_old);
197         m_animate_time_old = now;
198
199         // Draw console elements if visible
200         if (m_height > 0)
201         {
202                 drawBackground();
203                 drawText();
204                 drawPrompt();
205         }
206
207         gui::IGUIElement::draw();
208 }
209
210 void GUIChatConsole::reformatConsole()
211 {
212         s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better)
213         s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt
214         if (cols <= 0 || rows <= 0)
215                 cols = rows = 0;
216         recalculateConsolePosition();
217         m_chat_backend->reformat(cols, rows);
218 }
219
220 void GUIChatConsole::recalculateConsolePosition()
221 {
222         core::rect<s32> rect(0, 0, m_screensize.X, m_height);
223         DesiredRect = rect;
224         recalculateAbsolutePosition(false);
225 }
226
227 void GUIChatConsole::animate(u32 msec)
228 {
229         // animate the console height
230         s32 goal = m_open ? m_desired_height : 0;
231
232         // Set invisible if close animation finished (reset by openConsole)
233         // This function (animate()) is never called once its visibility becomes false so do not
234         //              actually set visible to false before the inhibited period is over
235         if (!m_open && m_height == 0 && m_open_inhibited == 0)
236                 IGUIElement::setVisible(false);
237
238         if (m_height != goal)
239         {
240                 s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0);
241                 if (max_change == 0)
242                         max_change = 1;
243
244                 if (m_height < goal)
245                 {
246                         // increase height
247                         if (m_height + max_change < goal)
248                                 m_height += max_change;
249                         else
250                                 m_height = goal;
251                 }
252                 else
253                 {
254                         // decrease height
255                         if (m_height > goal + max_change)
256                                 m_height -= max_change;
257                         else
258                                 m_height = goal;
259                 }
260
261                 recalculateConsolePosition();
262         }
263
264         // blink the cursor
265         if (m_cursor_blink_speed != 0.0)
266         {
267                 u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0);
268                 if (blink_increase == 0)
269                         blink_increase = 1;
270                 m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff);
271         }
272
273         // decrease open inhibit counter
274         if (m_open_inhibited > msec)
275                 m_open_inhibited -= msec;
276         else
277                 m_open_inhibited = 0;
278 }
279
280 void GUIChatConsole::drawBackground()
281 {
282         video::IVideoDriver* driver = Environment->getVideoDriver();
283         if (m_background != NULL)
284         {
285                 core::rect<s32> sourcerect(0, -m_height, m_screensize.X, 0);
286                 driver->draw2DImage(
287                         m_background,
288                         v2s32(0, 0),
289                         sourcerect,
290                         &AbsoluteClippingRect,
291                         m_background_color,
292                         false);
293         }
294         else
295         {
296                 driver->draw2DRectangle(
297                         m_background_color,
298                         core::rect<s32>(0, 0, m_screensize.X, m_height),
299                         &AbsoluteClippingRect);
300         }
301 }
302
303 void GUIChatConsole::drawText()
304 {
305         if (m_font == NULL)
306                 return;
307
308         ChatBuffer& buf = m_chat_backend->getConsoleBuffer();
309         for (u32 row = 0; row < buf.getRows(); ++row)
310         {
311                 const ChatFormattedLine& line = buf.getFormattedLine(row);
312                 if (line.fragments.empty())
313                         continue;
314
315                 s32 line_height = m_fontsize.Y;
316                 s32 y = row * line_height + m_height - m_desired_height;
317                 if (y + line_height < 0)
318                         continue;
319
320                 for (const ChatFormattedFragment &fragment : line.fragments) {
321                         s32 x = (fragment.column + 1) * m_fontsize.X;
322                         core::rect<s32> destrect(
323                                 x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y);
324
325
326                         #if USE_FREETYPE
327                         // Draw colored text if FreeType is enabled
328                                 irr::gui::CGUITTFont *tmp = dynamic_cast<irr::gui::CGUITTFont *>(m_font);
329                                 tmp->draw(
330                                         fragment.text,
331                                         destrect,
332                                         video::SColor(255, 255, 255, 255),
333                                         false,
334                                         false,
335                                         &AbsoluteClippingRect);
336                         #else
337                         // Otherwise use standard text
338                                 m_font->draw(
339                                         fragment.text.c_str(),
340                                         destrect,
341                                         video::SColor(255, 255, 255, 255),
342                                         false,
343                                         false,
344                                         &AbsoluteClippingRect);
345                         #endif
346                 }
347         }
348 }
349
350 void GUIChatConsole::drawPrompt()
351 {
352         if (!m_font)
353                 return;
354
355         u32 row = m_chat_backend->getConsoleBuffer().getRows();
356         s32 line_height = m_fontsize.Y;
357         s32 y = row * line_height + m_height - m_desired_height;
358
359         ChatPrompt& prompt = m_chat_backend->getPrompt();
360         std::wstring prompt_text = prompt.getVisiblePortion();
361
362         // FIXME Draw string at once, not character by character
363         // That will only work with the cursor once we have a monospace font
364         for (u32 i = 0; i < prompt_text.size(); ++i)
365         {
366                 wchar_t ws[2] = {prompt_text[i], 0};
367                 s32 x = (1 + i) * m_fontsize.X;
368                 core::rect<s32> destrect(
369                         x, y, x + m_fontsize.X, y + m_fontsize.Y);
370                 m_font->draw(
371                         ws,
372                         destrect,
373                         video::SColor(255, 255, 255, 255),
374                         false,
375                         false,
376                         &AbsoluteClippingRect);
377         }
378
379         // Draw the cursor during on periods
380         if ((m_cursor_blink & 0x8000) != 0)
381         {
382                 s32 cursor_pos = prompt.getVisibleCursorPosition();
383                 if (cursor_pos >= 0)
384                 {
385                         s32 cursor_len = prompt.getCursorLength();
386                         video::IVideoDriver* driver = Environment->getVideoDriver();
387                         s32 x = (1 + cursor_pos) * m_fontsize.X;
388                         core::rect<s32> destrect(
389                                 x,
390                                 y + m_fontsize.Y * (1.0 - m_cursor_height),
391                                 x + m_fontsize.X * MYMAX(cursor_len, 1),
392                                 y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1)
393                         );
394                         video::SColor cursor_color(255,255,255,255);
395                         driver->draw2DRectangle(
396                                 cursor_color,
397                                 destrect,
398                                 &AbsoluteClippingRect);
399                 }
400         }
401
402 }
403
404 bool GUIChatConsole::OnEvent(const SEvent& event)
405 {
406
407         ChatPrompt &prompt = m_chat_backend->getPrompt();
408
409         if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown)
410         {
411                 // Key input
412                 if (KeyPress(event.KeyInput) == getKeySetting("keymap_console")) {
413                         closeConsole();
414
415                         // inhibit open so the_game doesn't reopen immediately
416                         m_open_inhibited = 50;
417                         m_close_on_enter = false;
418                         return true;
419                 }
420
421                 if (event.KeyInput.Key == KEY_ESCAPE) {
422                         closeConsoleAtOnce();
423                         m_close_on_enter = false;
424                         // inhibit open so the_game doesn't reopen immediately
425                         m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu"
426                         return true;
427                 }
428                 else if(event.KeyInput.Key == KEY_PRIOR)
429                 {
430                         m_chat_backend->scrollPageUp();
431                         return true;
432                 }
433                 else if(event.KeyInput.Key == KEY_NEXT)
434                 {
435                         m_chat_backend->scrollPageDown();
436                         return true;
437                 }
438                 else if(event.KeyInput.Key == KEY_RETURN)
439                 {
440                         prompt.addToHistory(prompt.getLine());
441                         std::wstring text = prompt.replace(L"");
442                         m_client->typeChatMessage(text);
443                         if (m_close_on_enter) {
444                                 closeConsoleAtOnce();
445                                 m_close_on_enter = false;
446                         }
447                         return true;
448                 }
449                 else if(event.KeyInput.Key == KEY_UP)
450                 {
451                         // Up pressed
452                         // Move back in history
453                         prompt.historyPrev();
454                         return true;
455                 }
456                 else if(event.KeyInput.Key == KEY_DOWN)
457                 {
458                         // Down pressed
459                         // Move forward in history
460                         prompt.historyNext();
461                         return true;
462                 }
463                 else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT)
464                 {
465                         // Left/right pressed
466                         // Move/select character/word to the left depending on control and shift keys
467                         ChatPrompt::CursorOp op = event.KeyInput.Shift ?
468                                 ChatPrompt::CURSOROP_SELECT :
469                                 ChatPrompt::CURSOROP_MOVE;
470                         ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ?
471                                 ChatPrompt::CURSOROP_DIR_LEFT :
472                                 ChatPrompt::CURSOROP_DIR_RIGHT;
473                         ChatPrompt::CursorOpScope scope = event.KeyInput.Control ?
474                                 ChatPrompt::CURSOROP_SCOPE_WORD :
475                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
476                         prompt.cursorOperation(op, dir, scope);
477                         return true;
478                 }
479                 else if(event.KeyInput.Key == KEY_HOME)
480                 {
481                         // Home pressed
482                         // move to beginning of line
483                         prompt.cursorOperation(
484                                 ChatPrompt::CURSOROP_MOVE,
485                                 ChatPrompt::CURSOROP_DIR_LEFT,
486                                 ChatPrompt::CURSOROP_SCOPE_LINE);
487                         return true;
488                 }
489                 else if(event.KeyInput.Key == KEY_END)
490                 {
491                         // End pressed
492                         // move to end of line
493                         prompt.cursorOperation(
494                                 ChatPrompt::CURSOROP_MOVE,
495                                 ChatPrompt::CURSOROP_DIR_RIGHT,
496                                 ChatPrompt::CURSOROP_SCOPE_LINE);
497                         return true;
498                 }
499                 else if(event.KeyInput.Key == KEY_BACK)
500                 {
501                         // Backspace or Ctrl-Backspace pressed
502                         // delete character / word to the left
503                         ChatPrompt::CursorOpScope scope =
504                                 event.KeyInput.Control ?
505                                 ChatPrompt::CURSOROP_SCOPE_WORD :
506                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
507                         prompt.cursorOperation(
508                                 ChatPrompt::CURSOROP_DELETE,
509                                 ChatPrompt::CURSOROP_DIR_LEFT,
510                                 scope);
511                         return true;
512                 }
513                 else if(event.KeyInput.Key == KEY_DELETE)
514                 {
515                         // Delete or Ctrl-Delete pressed
516                         // delete character / word to the right
517                         ChatPrompt::CursorOpScope scope =
518                                 event.KeyInput.Control ?
519                                 ChatPrompt::CURSOROP_SCOPE_WORD :
520                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
521                         prompt.cursorOperation(
522                                 ChatPrompt::CURSOROP_DELETE,
523                                 ChatPrompt::CURSOROP_DIR_RIGHT,
524                                 scope);
525                         return true;
526                 }
527                 else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control)
528                 {
529                         // Ctrl-A pressed
530                         // Select all text
531                         prompt.cursorOperation(
532                                 ChatPrompt::CURSOROP_SELECT,
533                                 ChatPrompt::CURSOROP_DIR_LEFT, // Ignored
534                                 ChatPrompt::CURSOROP_SCOPE_LINE);
535                         return true;
536                 }
537                 else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control)
538                 {
539                         // Ctrl-C pressed
540                         // Copy text to clipboard
541                         if (prompt.getCursorLength() <= 0)
542                                 return true;
543                         std::wstring wselected = prompt.getSelection();
544                         std::string selected(wselected.begin(), wselected.end());
545                         Environment->getOSOperator()->copyToClipboard(selected.c_str());
546                         return true;
547                 }
548                 else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control)
549                 {
550                         // Ctrl-V pressed
551                         // paste text from clipboard
552                         if (prompt.getCursorLength() > 0) {
553                                 // Delete selected section of text
554                                 prompt.cursorOperation(
555                                         ChatPrompt::CURSOROP_DELETE,
556                                         ChatPrompt::CURSOROP_DIR_LEFT, // Ignored
557                                         ChatPrompt::CURSOROP_SCOPE_SELECTION);
558                         }
559                         IOSOperator *os_operator = Environment->getOSOperator();
560                         const c8 *text = os_operator->getTextFromClipboard();
561                         if (!text)
562                                 return true;
563                         std::basic_string<unsigned char> str((const unsigned char*)text);
564                         prompt.input(std::wstring(str.begin(), str.end()));
565                         return true;
566                 }
567                 else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control)
568                 {
569                         // Ctrl-X pressed
570                         // Cut text to clipboard
571                         if (prompt.getCursorLength() <= 0)
572                                 return true;
573                         std::wstring wselected = prompt.getSelection();
574                         std::string selected(wselected.begin(), wselected.end());
575                         Environment->getOSOperator()->copyToClipboard(selected.c_str());
576                         prompt.cursorOperation(
577                                 ChatPrompt::CURSOROP_DELETE,
578                                 ChatPrompt::CURSOROP_DIR_LEFT, // Ignored
579                                 ChatPrompt::CURSOROP_SCOPE_SELECTION);
580                         return true;
581                 }
582                 else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control)
583                 {
584                         // Ctrl-U pressed
585                         // kill line to left end
586                         prompt.cursorOperation(
587                                 ChatPrompt::CURSOROP_DELETE,
588                                 ChatPrompt::CURSOROP_DIR_LEFT,
589                                 ChatPrompt::CURSOROP_SCOPE_LINE);
590                         return true;
591                 }
592                 else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control)
593                 {
594                         // Ctrl-K pressed
595                         // kill line to right end
596                         prompt.cursorOperation(
597                                 ChatPrompt::CURSOROP_DELETE,
598                                 ChatPrompt::CURSOROP_DIR_RIGHT,
599                                 ChatPrompt::CURSOROP_SCOPE_LINE);
600                         return true;
601                 }
602                 else if(event.KeyInput.Key == KEY_TAB)
603                 {
604                         // Tab or Shift-Tab pressed
605                         // Nick completion
606                         std::list<std::string> names = m_client->getConnectedPlayerNames();
607                         bool backwards = event.KeyInput.Shift;
608                         prompt.nickCompletion(names, backwards);
609                         return true;
610                 } else if (!iswcntrl(event.KeyInput.Char) && !event.KeyInput.Control) {
611                         #if defined(__linux__) && (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9)
612                                 wchar_t wc = L'_';
613                                 mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) );
614                                 prompt.input(wc);
615                         #else
616                                 prompt.input(event.KeyInput.Char);
617                         #endif
618                         return true;
619                 }
620         }
621         else if(event.EventType == EET_MOUSE_INPUT_EVENT)
622         {
623                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
624                 {
625                         s32 rows = myround(-3.0 * event.MouseInput.Wheel);
626                         m_chat_backend->scroll(rows);
627                 }
628         }
629
630         return Parent ? Parent->OnEvent(event) : false;
631 }
632
633 void GUIChatConsole::setVisible(bool visible)
634 {
635         m_open = visible;
636         IGUIElement::setVisible(visible);
637         if (!visible) {
638                 m_height = 0;
639                 recalculateConsolePosition();
640         }
641 }
642