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