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