Close console when it loses focus but it is still on screen
[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 "main.h"  // for g_settings
28 #include "porting.h"
29 #include "tile.h"
30 #include "IGUIFont.h"
31 #include <string>
32
33 #include "gettext.h"
34
35 #if USE_FREETYPE
36 #include "xCGUITTFont.h"
37 #endif
38
39 inline u32 clamp_u8(s32 value)
40 {
41         return (u32) MYMIN(MYMAX(value, 0), 255);
42 }
43
44
45 GUIChatConsole::GUIChatConsole(
46                 gui::IGUIEnvironment* env,
47                 gui::IGUIElement* parent,
48                 s32 id,
49                 ChatBackend* backend,
50                 Client* client
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_screensize(v2u32(0,0)),
57         m_animate_time_old(0),
58         m_open(false),
59         m_height(0),
60         m_desired_height(0),
61         m_desired_height_fraction(0.0),
62         m_height_speed(5.0),
63         m_open_inhibited(0),
64         m_cursor_blink(0.0),
65         m_cursor_blink_speed(0.0),
66         m_cursor_height(0.0),
67         m_background(NULL),
68         m_background_color(255, 0, 0, 0),
69         m_font(NULL),
70         m_fontsize(0, 0)
71 {
72         m_animate_time_old = getTimeMs();
73
74         // load background settings
75         bool console_color_set = !g_settings->get("console_color").empty();
76         s32 console_alpha = g_settings->getS32("console_alpha");
77
78         // load the background texture depending on settings
79         m_background_color.setAlpha(clamp_u8(console_alpha));
80         if (console_color_set)
81         {
82                 v3f console_color = g_settings->getV3F("console_color");
83                 m_background_color.setRed(clamp_u8(myround(console_color.X)));
84                 m_background_color.setGreen(clamp_u8(myround(console_color.Y)));
85                 m_background_color.setBlue(clamp_u8(myround(console_color.Z)));
86         }
87         else
88         {
89                 m_background = env->getVideoDriver()->getTexture(getTexturePath("background_chat.jpg").c_str());
90                 m_background_color.setRed(255);
91                 m_background_color.setGreen(255);
92                 m_background_color.setBlue(255);
93         }
94
95         // load the font
96         // FIXME should a custom texture_path be searched too?
97         #if USE_FREETYPE
98         std::string font_name = g_settings->get("mono_font_path");
99         u16 font_size = g_settings->getU16("mono_font_size");
100         m_font = gui::CGUITTFont::createTTFont(env, font_name.c_str(), font_size);
101         #else
102         std::string font_name = "fontdejavusansmono.png";
103         m_font = env->getFont(getTexturePath(font_name).c_str());
104         #endif
105         if (m_font == NULL)
106         {
107                 dstream << "Unable to load font: " << font_name << std::endl;
108         }
109         else
110         {
111                 core::dimension2d<u32> dim = m_font->getDimension(L"M");
112                 m_fontsize = v2u32(dim.Width, dim.Height);
113                 dstream << "Font size: " << m_fontsize.X << " " << m_fontsize.Y << std::endl;
114         }
115         m_fontsize.X = MYMAX(m_fontsize.X, 1);
116         m_fontsize.Y = MYMAX(m_fontsize.Y, 1);
117
118         // set default cursor options
119         setCursor(true, true, 2.0, 0.1);
120 }
121
122 GUIChatConsole::~GUIChatConsole()
123 {
124 #if USE_FREETYPE
125         m_font->drop();
126 #endif
127 }
128
129 void GUIChatConsole::openConsole(f32 height)
130 {
131         m_open = true;
132         m_desired_height_fraction = height;
133         m_desired_height = height * m_screensize.Y;
134         reformatConsole();
135 }
136
137 bool GUIChatConsole::isOpen() const
138 {
139         return m_open;
140 }
141
142 bool GUIChatConsole::isOpenInhibited() const
143 {
144         return m_open_inhibited > 0;
145 }
146
147 void GUIChatConsole::closeConsole()
148 {
149         m_open = false;
150 }
151
152 void GUIChatConsole::closeConsoleAtOnce()
153 {
154         m_open = false;
155         m_height = 0;
156         recalculateConsolePosition();
157 }
158
159 f32 GUIChatConsole::getDesiredHeight() const
160 {
161         return m_desired_height_fraction;
162 }
163
164 void GUIChatConsole::setCursor(
165         bool visible, bool blinking, f32 blink_speed, f32 relative_height)
166 {
167         if (visible)
168         {
169                 if (blinking)
170                 {
171                         // leave m_cursor_blink unchanged
172                         m_cursor_blink_speed = blink_speed;
173                 }
174                 else
175                 {
176                         m_cursor_blink = 0x8000;  // on
177                         m_cursor_blink_speed = 0.0;
178                 }
179         }
180         else
181         {
182                 m_cursor_blink = 0;  // off
183                 m_cursor_blink_speed = 0.0;
184         }
185         m_cursor_height = relative_height;
186 }
187
188 void GUIChatConsole::draw()
189 {
190         if(!IsVisible)
191                 return;
192
193         video::IVideoDriver* driver = Environment->getVideoDriver();
194
195         // Check screen size
196         v2u32 screensize = driver->getScreenSize();
197         if (screensize != m_screensize)
198         {
199                 // screen size has changed
200                 // scale current console height to new window size
201                 if (m_screensize.Y != 0)
202                         m_height = m_height * screensize.Y / m_screensize.Y;
203                 m_desired_height = m_desired_height_fraction * m_screensize.Y;
204                 m_screensize = screensize;
205                 reformatConsole();
206         }
207
208         // Animation
209         u32 now = getTimeMs();
210         animate(now - m_animate_time_old);
211         m_animate_time_old = now;
212
213         // Draw console elements if visible
214         if (m_height > 0)
215         {
216                 drawBackground();
217                 drawText();
218                 drawPrompt();
219         }
220
221         gui::IGUIElement::draw();
222 }
223
224 void GUIChatConsole::reformatConsole()
225 {
226         s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better)
227         s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt
228         if (cols <= 0 || rows <= 0)
229                 cols = rows = 0;
230         m_chat_backend->reformat(cols, rows);
231 }
232
233 void GUIChatConsole::recalculateConsolePosition()
234 {
235         core::rect<s32> rect(0, 0, m_screensize.X, m_height);
236         DesiredRect = rect;
237         recalculateAbsolutePosition(false);
238 }
239
240 void GUIChatConsole::animate(u32 msec)
241 {
242         // animate the console height
243         s32 goal = m_open ? m_desired_height : 0;
244         if (m_height != goal)
245         {
246                 s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0);
247                 if (max_change == 0)
248                         max_change = 1;
249
250                 if (m_height < goal)
251                 {
252                         // increase height
253                         if (m_height + max_change < goal)
254                                 m_height += max_change;
255                         else
256                                 m_height = goal;
257                 }
258                 else
259                 {
260                         // decrease height
261                         if (m_height > goal + max_change)
262                                 m_height -= max_change;
263                         else
264                                 m_height = goal;
265                 }
266
267                 recalculateConsolePosition();
268         }
269
270         // blink the cursor
271         if (m_cursor_blink_speed != 0.0)
272         {
273                 u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0);
274                 if (blink_increase == 0)
275                         blink_increase = 1;
276                 m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff);
277         }
278
279         // decrease open inhibit counter
280         if (m_open_inhibited > msec)
281                 m_open_inhibited -= msec;
282         else
283                 m_open_inhibited = 0;
284 }
285
286 void GUIChatConsole::drawBackground()
287 {
288         video::IVideoDriver* driver = Environment->getVideoDriver();
289         if (m_background != NULL)
290         {
291                 core::rect<s32> sourcerect(0, -m_height, m_screensize.X, 0);
292                 driver->draw2DImage(
293                         m_background,
294                         v2s32(0, 0),
295                         sourcerect,
296                         &AbsoluteClippingRect,
297                         m_background_color,
298                         false);
299         }
300         else
301         {
302                 driver->draw2DRectangle(
303                         m_background_color,
304                         core::rect<s32>(0, 0, m_screensize.X, m_height),
305                         &AbsoluteClippingRect);
306         }
307 }
308
309 void GUIChatConsole::drawText()
310 {
311         if (m_font == NULL)
312                 return;
313
314         ChatBuffer& buf = m_chat_backend->getConsoleBuffer();
315         for (u32 row = 0; row < buf.getRows(); ++row)
316         {
317                 const ChatFormattedLine& line = buf.getFormattedLine(row);
318                 if (line.fragments.empty())
319                         continue;
320
321                 s32 line_height = m_fontsize.Y;
322                 s32 y = row * line_height + m_height - m_desired_height;
323                 if (y + line_height < 0)
324                         continue;
325
326                 for (u32 i = 0; i < line.fragments.size(); ++i)
327                 {
328                         const ChatFormattedFragment& fragment = line.fragments[i];
329                         s32 x = (fragment.column + 1) * m_fontsize.X;
330                         core::rect<s32> destrect(
331                                 x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y);
332                         m_font->draw(
333                                 fragment.text.c_str(),
334                                 destrect,
335                                 video::SColor(255, 255, 255, 255),
336                                 false,
337                                 false,
338                                 &AbsoluteClippingRect);
339                 }
340         }
341 }
342
343 void GUIChatConsole::drawPrompt()
344 {
345         if (m_font == NULL)
346                 return;
347
348         u32 row = m_chat_backend->getConsoleBuffer().getRows();
349         s32 line_height = m_fontsize.Y;
350         s32 y = row * line_height + m_height - m_desired_height;
351
352         ChatPrompt& prompt = m_chat_backend->getPrompt();
353         std::wstring prompt_text = prompt.getVisiblePortion();
354
355         // FIXME Draw string at once, not character by character
356         // That will only work with the cursor once we have a monospace font
357         for (u32 i = 0; i < prompt_text.size(); ++i)
358         {
359                 wchar_t ws[2] = {prompt_text[i], 0};
360                 s32 x = (1 + i) * m_fontsize.X;
361                 core::rect<s32> destrect(
362                         x, y, x + m_fontsize.X, y + m_fontsize.Y);
363                 m_font->draw(
364                         ws,
365                         destrect,
366                         video::SColor(255, 255, 255, 255),
367                         false,
368                         false,
369                         &AbsoluteClippingRect);
370         }
371
372         // Draw the cursor during on periods
373         if ((m_cursor_blink & 0x8000) != 0)
374         {
375                 s32 cursor_pos = prompt.getVisibleCursorPosition();
376                 if (cursor_pos >= 0)
377                 {
378                         video::IVideoDriver* driver = Environment->getVideoDriver();
379                         s32 x = (1 + cursor_pos) * m_fontsize.X;
380                         core::rect<s32> destrect(
381                                 x,
382                                 y + (1.0-m_cursor_height) * m_fontsize.Y,
383                                 x + m_fontsize.X,
384                                 y + m_fontsize.Y);
385                         video::SColor cursor_color(255,255,255,255);
386                         driver->draw2DRectangle(
387                                 cursor_color,
388                                 destrect,
389                                 &AbsoluteClippingRect);
390                 }
391         }
392
393 }
394
395 bool GUIChatConsole::OnEvent(const SEvent& event)
396 {
397         if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown)
398         {
399                 // Key input
400                 if(KeyPress(event.KeyInput) == getKeySetting("keymap_console"))
401                 {
402                         closeConsole();
403                         Environment->removeFocus(this);
404
405                         // inhibit open so the_game doesn't reopen immediately
406                         m_open_inhibited = 50;
407                         return true;
408                 }
409                 else if(event.KeyInput.Key == KEY_ESCAPE)
410                 {
411                         closeConsoleAtOnce();
412                         Environment->removeFocus(this);
413                         // the_game will open the pause menu
414                         return true;
415                 }
416                 else if(event.KeyInput.Key == KEY_PRIOR)
417                 {
418                         m_chat_backend->scrollPageUp();
419                         return true;
420                 }
421                 else if(event.KeyInput.Key == KEY_NEXT)
422                 {
423                         m_chat_backend->scrollPageDown();
424                         return true;
425                 }
426                 else if(event.KeyInput.Key == KEY_RETURN)
427                 {
428                         std::wstring text = m_chat_backend->getPrompt().submit();
429                         m_client->typeChatMessage(text);
430                         return true;
431                 }
432                 else if(event.KeyInput.Key == KEY_UP)
433                 {
434                         // Up pressed
435                         // Move back in history
436                         m_chat_backend->getPrompt().historyPrev();
437                         return true;
438                 }
439                 else if(event.KeyInput.Key == KEY_DOWN)
440                 {
441                         // Down pressed
442                         // Move forward in history
443                         m_chat_backend->getPrompt().historyNext();
444                         return true;
445                 }
446                 else if(event.KeyInput.Key == KEY_LEFT)
447                 {
448                         // Left or Ctrl-Left pressed
449                         // move character / word to the left
450                         ChatPrompt::CursorOpScope scope =
451                                 event.KeyInput.Control ?
452                                 ChatPrompt::CURSOROP_SCOPE_WORD :
453                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
454                         m_chat_backend->getPrompt().cursorOperation(
455                                 ChatPrompt::CURSOROP_MOVE,
456                                 ChatPrompt::CURSOROP_DIR_LEFT,
457                                 scope);
458                         return true;
459                 }
460                 else if(event.KeyInput.Key == KEY_RIGHT)
461                 {
462                         // Right or Ctrl-Right pressed
463                         // move character / word to the right
464                         ChatPrompt::CursorOpScope scope =
465                                 event.KeyInput.Control ?
466                                 ChatPrompt::CURSOROP_SCOPE_WORD :
467                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
468                         m_chat_backend->getPrompt().cursorOperation(
469                                 ChatPrompt::CURSOROP_MOVE,
470                                 ChatPrompt::CURSOROP_DIR_RIGHT,
471                                 scope);
472                         return true;
473                 }
474                 else if(event.KeyInput.Key == KEY_HOME)
475                 {
476                         // Home pressed
477                         // move to beginning of line
478                         m_chat_backend->getPrompt().cursorOperation(
479                                 ChatPrompt::CURSOROP_MOVE,
480                                 ChatPrompt::CURSOROP_DIR_LEFT,
481                                 ChatPrompt::CURSOROP_SCOPE_LINE);
482                         return true;
483                 }
484                 else if(event.KeyInput.Key == KEY_END)
485                 {
486                         // End pressed
487                         // move to end of line
488                         m_chat_backend->getPrompt().cursorOperation(
489                                 ChatPrompt::CURSOROP_MOVE,
490                                 ChatPrompt::CURSOROP_DIR_RIGHT,
491                                 ChatPrompt::CURSOROP_SCOPE_LINE);
492                         return true;
493                 }
494                 else if(event.KeyInput.Key == KEY_BACK)
495                 {
496                         // Backspace or Ctrl-Backspace pressed
497                         // delete character / word to the left
498                         ChatPrompt::CursorOpScope scope =
499                                 event.KeyInput.Control ?
500                                 ChatPrompt::CURSOROP_SCOPE_WORD :
501                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
502                         m_chat_backend->getPrompt().cursorOperation(
503                                 ChatPrompt::CURSOROP_DELETE,
504                                 ChatPrompt::CURSOROP_DIR_LEFT,
505                                 scope);
506                         return true;
507                 }
508                 else if(event.KeyInput.Key == KEY_DELETE)
509                 {
510                         // Delete or Ctrl-Delete pressed
511                         // delete character / word to the right
512                         ChatPrompt::CursorOpScope scope =
513                                 event.KeyInput.Control ?
514                                 ChatPrompt::CURSOROP_SCOPE_WORD :
515                                 ChatPrompt::CURSOROP_SCOPE_CHARACTER;
516                         m_chat_backend->getPrompt().cursorOperation(
517                                 ChatPrompt::CURSOROP_DELETE,
518                                 ChatPrompt::CURSOROP_DIR_RIGHT,
519                                 scope);
520                         return true;
521                 }
522                 else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control)
523                 {
524                         // Ctrl-U pressed
525                         // kill line to left end
526                         m_chat_backend->getPrompt().cursorOperation(
527                                 ChatPrompt::CURSOROP_DELETE,
528                                 ChatPrompt::CURSOROP_DIR_LEFT,
529                                 ChatPrompt::CURSOROP_SCOPE_LINE);
530                         return true;
531                 }
532                 else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control)
533                 {
534                         // Ctrl-K pressed
535                         // kill line to right end
536                         m_chat_backend->getPrompt().cursorOperation(
537                                 ChatPrompt::CURSOROP_DELETE,
538                                 ChatPrompt::CURSOROP_DIR_RIGHT,
539                                 ChatPrompt::CURSOROP_SCOPE_LINE);
540                         return true;
541                 }
542                 else if(event.KeyInput.Key == KEY_TAB)
543                 {
544                         // Tab or Shift-Tab pressed
545                         // Nick completion
546                         std::list<std::string> names = m_client->getConnectedPlayerNames();
547                         bool backwards = event.KeyInput.Shift;
548                         m_chat_backend->getPrompt().nickCompletion(names, backwards);
549                         return true;
550                 }
551                 else if(event.KeyInput.Char != 0 && !event.KeyInput.Control)
552                 {
553                         m_chat_backend->getPrompt().input(event.KeyInput.Char);
554                         return true;
555                 }
556         }
557         else if(event.EventType == EET_MOUSE_INPUT_EVENT)
558         {
559                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
560                 {
561                         s32 rows = myround(-3.0 * event.MouseInput.Wheel);
562                         m_chat_backend->scroll(rows);
563                 }
564         }
565
566         return Parent ? Parent->OnEvent(event) : false;
567 }
568