]> git.lizzy.rs Git - dragonfireclient.git/blob - src/chat.cpp
Implement #6096
[dragonfireclient.git] / src / chat.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 "chat.h"
21 #include "debug.h"
22 #include "config.h"
23 #include "util/strfnd.h"
24 #include <cctype>
25 #include <sstream>
26 #include "util/string.h"
27 #include "util/numeric.h"
28
29 ChatBuffer::ChatBuffer(u32 scrollback):
30         m_scrollback(scrollback)
31 {
32         if (m_scrollback == 0)
33                 m_scrollback = 1;
34         m_empty_formatted_line.first = true;
35 }
36
37 void ChatBuffer::addLine(std::wstring name, std::wstring text)
38 {
39         ChatLine line(name, text);
40         m_unformatted.push_back(line);
41
42         if (m_rows > 0)
43         {
44                 // m_formatted is valid and must be kept valid
45                 bool scrolled_at_bottom = (m_scroll == getBottomScrollPos());
46                 u32 num_added = formatChatLine(line, m_cols, m_formatted);
47                 if (scrolled_at_bottom)
48                         m_scroll += num_added;
49         }
50
51         // Limit number of lines by m_scrollback
52         if (m_unformatted.size() > m_scrollback)
53         {
54                 deleteOldest(m_unformatted.size() - m_scrollback);
55         }
56 }
57
58 void ChatBuffer::clear()
59 {
60         m_unformatted.clear();
61         m_formatted.clear();
62         m_scroll = 0;
63 }
64
65 u32 ChatBuffer::getLineCount() const
66 {
67         return m_unformatted.size();
68 }
69
70 const ChatLine& ChatBuffer::getLine(u32 index) const
71 {
72         assert(index < getLineCount()); // pre-condition
73         return m_unformatted[index];
74 }
75
76 void ChatBuffer::step(f32 dtime)
77 {
78         for (ChatLine &line : m_unformatted) {
79                 line.age += dtime;
80         }
81 }
82
83 void ChatBuffer::deleteOldest(u32 count)
84 {
85         bool at_bottom = (m_scroll == getBottomScrollPos());
86
87         u32 del_unformatted = 0;
88         u32 del_formatted = 0;
89
90         while (count > 0 && del_unformatted < m_unformatted.size())
91         {
92                 ++del_unformatted;
93
94                 // keep m_formatted in sync
95                 if (del_formatted < m_formatted.size())
96                 {
97
98                         sanity_check(m_formatted[del_formatted].first);
99                         ++del_formatted;
100                         while (del_formatted < m_formatted.size() &&
101                                         !m_formatted[del_formatted].first)
102                                 ++del_formatted;
103                 }
104
105                 --count;
106         }
107
108         m_unformatted.erase(m_unformatted.begin(), m_unformatted.begin() + del_unformatted);
109         m_formatted.erase(m_formatted.begin(), m_formatted.begin() + del_formatted);
110
111         if (at_bottom)
112                 m_scroll = getBottomScrollPos();
113         else
114                 scrollAbsolute(m_scroll - del_formatted);
115 }
116
117 void ChatBuffer::deleteByAge(f32 maxAge)
118 {
119         u32 count = 0;
120         while (count < m_unformatted.size() && m_unformatted[count].age > maxAge)
121                 ++count;
122         deleteOldest(count);
123 }
124
125 u32 ChatBuffer::getColumns() const
126 {
127         return m_cols;
128 }
129
130 u32 ChatBuffer::getRows() const
131 {
132         return m_rows;
133 }
134
135 void ChatBuffer::reformat(u32 cols, u32 rows)
136 {
137         if (cols == 0 || rows == 0)
138         {
139                 // Clear formatted buffer
140                 m_cols = 0;
141                 m_rows = 0;
142                 m_scroll = 0;
143                 m_formatted.clear();
144         }
145         else if (cols != m_cols || rows != m_rows)
146         {
147                 // TODO: Avoid reformatting ALL lines (even invisible ones)
148                 // each time the console size changes.
149
150                 // Find out the scroll position in *unformatted* lines
151                 u32 restore_scroll_unformatted = 0;
152                 u32 restore_scroll_formatted = 0;
153                 bool at_bottom = (m_scroll == getBottomScrollPos());
154                 if (!at_bottom)
155                 {
156                         for (s32 i = 0; i < m_scroll; ++i)
157                         {
158                                 if (m_formatted[i].first)
159                                         ++restore_scroll_unformatted;
160                         }
161                 }
162
163                 // If number of columns change, reformat everything
164                 if (cols != m_cols)
165                 {
166                         m_formatted.clear();
167                         for (u32 i = 0; i < m_unformatted.size(); ++i)
168                         {
169                                 if (i == restore_scroll_unformatted)
170                                         restore_scroll_formatted = m_formatted.size();
171                                 formatChatLine(m_unformatted[i], cols, m_formatted);
172                         }
173                 }
174
175                 // Update the console size
176                 m_cols = cols;
177                 m_rows = rows;
178
179                 // Restore the scroll position
180                 if (at_bottom)
181                 {
182                         scrollBottom();
183                 }
184                 else
185                 {
186                         scrollAbsolute(restore_scroll_formatted);
187                 }
188         }
189 }
190
191 const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const
192 {
193         s32 index = m_scroll + (s32) row;
194         if (index >= 0 && index < (s32) m_formatted.size())
195                 return m_formatted[index];
196
197         return m_empty_formatted_line;
198 }
199
200 void ChatBuffer::scroll(s32 rows)
201 {
202         scrollAbsolute(m_scroll + rows);
203 }
204
205 void ChatBuffer::scrollAbsolute(s32 scroll)
206 {
207         s32 top = getTopScrollPos();
208         s32 bottom = getBottomScrollPos();
209
210         m_scroll = scroll;
211         if (m_scroll < top)
212                 m_scroll = top;
213         if (m_scroll > bottom)
214                 m_scroll = bottom;
215 }
216
217 void ChatBuffer::scrollBottom()
218 {
219         m_scroll = getBottomScrollPos();
220 }
221
222 void ChatBuffer::scrollTop()
223 {
224         m_scroll = getTopScrollPos();
225 }
226
227 u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols,
228                 std::vector<ChatFormattedLine>& destination) const
229 {
230         u32 num_added = 0;
231         std::vector<ChatFormattedFragment> next_frags;
232         ChatFormattedLine next_line;
233         ChatFormattedFragment temp_frag;
234         u32 out_column = 0;
235         u32 in_pos = 0;
236         u32 hanging_indentation = 0;
237
238         // Format the sender name and produce fragments
239         if (!line.name.empty()) {
240                 temp_frag.text = L"<";
241                 temp_frag.column = 0;
242                 //temp_frag.bold = 0;
243                 next_frags.push_back(temp_frag);
244                 temp_frag.text = line.name;
245                 temp_frag.column = 0;
246                 //temp_frag.bold = 1;
247                 next_frags.push_back(temp_frag);
248                 temp_frag.text = L"> ";
249                 temp_frag.column = 0;
250                 //temp_frag.bold = 0;
251                 next_frags.push_back(temp_frag);
252         }
253
254         std::wstring name_sanitized = line.name.c_str();
255
256         // Choose an indentation level
257         if (line.name.empty()) {
258                 // Server messages
259                 hanging_indentation = 0;
260         } else if (name_sanitized.size() + 3 <= cols/2) {
261                 // Names shorter than about half the console width
262                 hanging_indentation = line.name.size() + 3;
263         } else {
264                 // Very long names
265                 hanging_indentation = 2;
266         }
267         //EnrichedString line_text(line.text);
268
269         next_line.first = true;
270         bool text_processing = false;
271
272         // Produce fragments and layout them into lines
273         while (!next_frags.empty() || in_pos < line.text.size())
274         {
275                 // Layout fragments into lines
276                 while (!next_frags.empty())
277                 {
278                         ChatFormattedFragment& frag = next_frags[0];
279                         if (frag.text.size() <= cols - out_column)
280                         {
281                                 // Fragment fits into current line
282                                 frag.column = out_column;
283                                 next_line.fragments.push_back(frag);
284                                 out_column += frag.text.size();
285                                 next_frags.erase(next_frags.begin());
286                         }
287                         else
288                         {
289                                 // Fragment does not fit into current line
290                                 // So split it up
291                                 temp_frag.text = frag.text.substr(0, cols - out_column);
292                                 temp_frag.column = out_column;
293                                 //temp_frag.bold = frag.bold;
294                                 next_line.fragments.push_back(temp_frag);
295                                 frag.text = frag.text.substr(cols - out_column);
296                                 out_column = cols;
297                         }
298                         if (out_column == cols || text_processing)
299                         {
300                                 // End the current line
301                                 destination.push_back(next_line);
302                                 num_added++;
303                                 next_line.fragments.clear();
304                                 next_line.first = false;
305
306                                 out_column = text_processing ? hanging_indentation : 0;
307                         }
308                 }
309
310                 // Produce fragment
311                 if (in_pos < line.text.size())
312                 {
313                         u32 remaining_in_input = line.text.size() - in_pos;
314                         u32 remaining_in_output = cols - out_column;
315
316                         // Determine a fragment length <= the minimum of
317                         // remaining_in_{in,out}put. Try to end the fragment
318                         // on a word boundary.
319                         u32 frag_length = 1, space_pos = 0;
320                         while (frag_length < remaining_in_input &&
321                                         frag_length < remaining_in_output)
322                         {
323                                 if (iswspace(line.text.getString()[in_pos + frag_length]))
324                                         space_pos = frag_length;
325                                 ++frag_length;
326                         }
327                         if (space_pos != 0 && frag_length < remaining_in_input)
328                                 frag_length = space_pos + 1;
329
330                         temp_frag.text = line.text.substr(in_pos, frag_length);
331                         temp_frag.column = 0;
332                         //temp_frag.bold = 0;
333                         next_frags.push_back(temp_frag);
334                         in_pos += frag_length;
335                         text_processing = true;
336                 }
337         }
338
339         // End the last line
340         if (num_added == 0 || !next_line.fragments.empty())
341         {
342                 destination.push_back(next_line);
343                 num_added++;
344         }
345
346         return num_added;
347 }
348
349 s32 ChatBuffer::getTopScrollPos() const
350 {
351         s32 formatted_count = (s32) m_formatted.size();
352         s32 rows = (s32) m_rows;
353         if (rows == 0)
354                 return 0;
355
356         if (formatted_count <= rows)
357                 return formatted_count - rows;
358
359         return 0;
360 }
361
362 s32 ChatBuffer::getBottomScrollPos() const
363 {
364         s32 formatted_count = (s32) m_formatted.size();
365         s32 rows = (s32) m_rows;
366         if (rows == 0)
367                 return 0;
368
369         return formatted_count - rows;
370 }
371
372 void ChatBuffer::resize(u32 scrollback) {
373         m_scrollback = scrollback;
374         if (m_unformatted.size() > m_scrollback)
375         {
376                 deleteOldest(m_unformatted.size() - m_scrollback);
377         }       
378 }
379
380
381 ChatPrompt::ChatPrompt(const std::wstring &prompt, u32 history_limit):
382         m_prompt(prompt),
383         m_history_limit(history_limit)
384 {
385 }
386
387 void ChatPrompt::input(wchar_t ch)
388 {
389         m_line.insert(m_cursor, 1, ch);
390         m_cursor++;
391         clampView();
392         m_nick_completion_start = 0;
393         m_nick_completion_end = 0;
394 }
395
396 void ChatPrompt::input(const std::wstring &str)
397 {
398         m_line.insert(m_cursor, str);
399         m_cursor += str.size();
400         clampView();
401         m_nick_completion_start = 0;
402         m_nick_completion_end = 0;
403 }
404
405 void ChatPrompt::addToHistory(std::wstring line)
406 {
407         if (!line.empty())
408                 m_history.push_back(line);
409         if (m_history.size() > m_history_limit)
410                 m_history.erase(m_history.begin());
411         m_history_index = m_history.size();
412 }
413
414 void ChatPrompt::clear()
415 {
416         m_line.clear();
417         m_view = 0;
418         m_cursor = 0;
419         m_nick_completion_start = 0;
420         m_nick_completion_end = 0;
421 }
422
423 std::wstring ChatPrompt::replace(std::wstring line)
424 {
425         std::wstring old_line = m_line;
426         m_line =  line;
427         m_view = m_cursor = line.size();
428         clampView();
429         m_nick_completion_start = 0;
430         m_nick_completion_end = 0;
431         return old_line;
432 }
433
434 void ChatPrompt::historyPrev()
435 {
436         if (m_history_index != 0)
437         {
438                 --m_history_index;
439                 replace(m_history[m_history_index]);
440         }
441 }
442
443 void ChatPrompt::historyNext()
444 {
445         if (m_history_index + 1 >= m_history.size())
446         {
447                 m_history_index = m_history.size();
448                 replace(L"");
449         }
450         else
451         {
452                 ++m_history_index;
453                 replace(m_history[m_history_index]);
454         }
455 }
456
457 void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwards)
458 {
459         // Two cases:
460         // (a) m_nick_completion_start == m_nick_completion_end == 0
461         //     Then no previous nick completion is active.
462         //     Get the word around the cursor and replace with any nick
463         //     that has that word as a prefix.
464         // (b) else, continue a previous nick completion.
465         //     m_nick_completion_start..m_nick_completion_end are the
466         //     interval where the originally used prefix was. Cycle
467         //     through the list of completions of that prefix.
468         u32 prefix_start = m_nick_completion_start;
469         u32 prefix_end = m_nick_completion_end;
470         bool initial = (prefix_end == 0);
471         if (initial)
472         {
473                 // no previous nick completion is active
474                 prefix_start = prefix_end = m_cursor;
475                 while (prefix_start > 0 && !iswspace(m_line[prefix_start-1]))
476                         --prefix_start;
477                 while (prefix_end < m_line.size() && !iswspace(m_line[prefix_end]))
478                         ++prefix_end;
479                 if (prefix_start == prefix_end)
480                         return;
481         }
482         std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
483
484         // find all names that start with the selected prefix
485         std::vector<std::wstring> completions;
486         for (const std::string &name : names) {
487                 if (str_starts_with(narrow_to_wide(name), prefix, true)) {
488                         std::wstring completion = narrow_to_wide(name);
489                         if (prefix_start == 0)
490                                 completion += L": ";
491                         completions.push_back(completion);
492                 }
493         }
494
495         if (completions.empty())
496                 return;
497
498         // find a replacement string and the word that will be replaced
499         u32 word_end = prefix_end;
500         u32 replacement_index = 0;
501         if (!initial)
502         {
503                 while (word_end < m_line.size() && !iswspace(m_line[word_end]))
504                         ++word_end;
505                 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
506
507                 // cycle through completions
508                 for (u32 i = 0; i < completions.size(); ++i)
509                 {
510                         if (str_equal(word, completions[i], true))
511                         {
512                                 if (backwards)
513                                         replacement_index = i + completions.size() - 1;
514                                 else
515                                         replacement_index = i + 1;
516                                 replacement_index %= completions.size();
517                                 break;
518                         }
519                 }
520         }
521         std::wstring replacement = completions[replacement_index];
522         if (word_end < m_line.size() && iswspace(m_line[word_end]))
523                 ++word_end;
524
525         // replace existing word with replacement word,
526         // place the cursor at the end and record the completion prefix
527         m_line.replace(prefix_start, word_end - prefix_start, replacement);
528         m_cursor = prefix_start + replacement.size();
529         clampView();
530         m_nick_completion_start = prefix_start;
531         m_nick_completion_end = prefix_end;
532 }
533
534 void ChatPrompt::reformat(u32 cols)
535 {
536         if (cols <= m_prompt.size())
537         {
538                 m_cols = 0;
539                 m_view = m_cursor;
540         }
541         else
542         {
543                 s32 length = m_line.size();
544                 bool was_at_end = (m_view + m_cols >= length + 1);
545                 m_cols = cols - m_prompt.size();
546                 if (was_at_end)
547                         m_view = length;
548                 clampView();
549         }
550 }
551
552 std::wstring ChatPrompt::getVisiblePortion() const
553 {
554         return m_prompt + m_line.substr(m_view, m_cols);
555 }
556
557 s32 ChatPrompt::getVisibleCursorPosition() const
558 {
559         return m_cursor - m_view + m_prompt.size();
560 }
561
562 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
563 {
564         s32 old_cursor = m_cursor;
565         s32 new_cursor = m_cursor;
566
567         s32 length = m_line.size();
568         s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
569
570         switch (scope) {
571         case CURSOROP_SCOPE_CHARACTER:
572                 new_cursor += increment;
573                 break;
574         case CURSOROP_SCOPE_WORD:
575                 if (dir == CURSOROP_DIR_RIGHT) {
576                         // skip one word to the right
577                         while (new_cursor < length && iswspace(m_line[new_cursor]))
578                                 new_cursor++;
579                         while (new_cursor < length && !iswspace(m_line[new_cursor]))
580                                 new_cursor++;
581                         while (new_cursor < length && iswspace(m_line[new_cursor]))
582                                 new_cursor++;
583                 } else {
584                         // skip one word to the left
585                         while (new_cursor >= 1 && iswspace(m_line[new_cursor - 1]))
586                                 new_cursor--;
587                         while (new_cursor >= 1 && !iswspace(m_line[new_cursor - 1]))
588                                 new_cursor--;
589                 }
590                 break;
591         case CURSOROP_SCOPE_LINE:
592                 new_cursor += increment * length;
593                 break;
594         case CURSOROP_SCOPE_SELECTION:
595                 break;
596         }
597
598         new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
599
600         switch (op) {
601         case CURSOROP_MOVE:
602                 m_cursor = new_cursor;
603                 m_cursor_len = 0;
604                 break;
605         case CURSOROP_DELETE:
606                 if (m_cursor_len > 0) { // Delete selected text first
607                         m_line.erase(m_cursor, m_cursor_len);
608                 } else {
609                         m_cursor = MYMIN(new_cursor, old_cursor);
610                         m_line.erase(m_cursor, abs(new_cursor - old_cursor));
611                 }
612                 m_cursor_len = 0;
613                 break;
614         case CURSOROP_SELECT:
615                 if (scope == CURSOROP_SCOPE_LINE) {
616                         m_cursor = 0;
617                         m_cursor_len = length;
618                 } else {
619                         m_cursor = MYMIN(new_cursor, old_cursor);
620                         m_cursor_len += abs(new_cursor - old_cursor);
621                         m_cursor_len = MYMIN(m_cursor_len, length - m_cursor);
622                 }
623                 break;
624         }
625
626         clampView();
627
628         m_nick_completion_start = 0;
629         m_nick_completion_end = 0;
630 }
631
632 void ChatPrompt::clampView()
633 {
634         s32 length = m_line.size();
635         if (length + 1 <= m_cols)
636         {
637                 m_view = 0;
638         }
639         else
640         {
641                 m_view = MYMIN(m_view, length + 1 - m_cols);
642                 m_view = MYMIN(m_view, m_cursor);
643                 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
644                 m_view = MYMAX(m_view, 0);
645         }
646 }
647
648
649
650 ChatBackend::ChatBackend():
651         m_console_buffer(500),
652         m_recent_buffer(6),
653         m_prompt(L"]", 500)
654 {
655 }
656
657 void ChatBackend::addMessage(std::wstring name, std::wstring text)
658 {
659         // Note: A message may consist of multiple lines, for example the MOTD.
660         text = translate_string(text);
661         WStrfnd fnd(text);
662         while (!fnd.at_end())
663         {
664                 std::wstring line = fnd.next(L"\n");
665                 m_console_buffer.addLine(name, line);
666                 m_recent_buffer.addLine(name, line);
667         }
668 }
669
670 void ChatBackend::addUnparsedMessage(std::wstring message)
671 {
672         // TODO: Remove the need to parse chat messages client-side, by sending
673         // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
674
675         if (message.size() >= 2 && message[0] == L'<')
676         {
677                 std::size_t closing = message.find_first_of(L'>', 1);
678                 if (closing != std::wstring::npos &&
679                                 closing + 2 <= message.size() &&
680                                 message[closing+1] == L' ')
681                 {
682                         std::wstring name = message.substr(1, closing - 1);
683                         std::wstring text = message.substr(closing + 2);
684                         addMessage(name, text);
685                         return;
686                 }
687         }
688
689         // Unable to parse, probably a server message.
690         addMessage(L"", message);
691 }
692
693 ChatBuffer& ChatBackend::getConsoleBuffer()
694 {
695         return m_console_buffer;
696 }
697
698 ChatBuffer& ChatBackend::getRecentBuffer()
699 {
700         return m_recent_buffer;
701 }
702
703 EnrichedString ChatBackend::getRecentChat()
704 {
705         EnrichedString result;
706         for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i)
707         {
708                 const ChatLine& line = m_recent_buffer.getLine(i);
709                 if (i != 0)
710                         result += L"\n";
711                 if (!line.name.empty()) {
712                         result += L"<";
713                         result += line.name;
714                         result += L"> ";
715                 }
716                 result += line.text;
717         }
718         return result;
719 }
720
721 ChatPrompt& ChatBackend::getPrompt()
722 {
723         return m_prompt;
724 }
725
726 void ChatBackend::reformat(u32 cols, u32 rows)
727 {
728         m_console_buffer.reformat(cols, rows);
729
730         // no need to reformat m_recent_buffer, its formatted lines
731         // are not used
732
733         m_prompt.reformat(cols);
734 }
735
736 void ChatBackend::clearRecentChat()
737 {
738         m_recent_buffer.clear();
739 }
740
741
742 void ChatBackend::applySettings(Settings* settings) {
743         m_recent_buffer.resize(settings->getU32("recent_chat_size"));
744 }
745
746 void ChatBackend::step(float dtime)
747 {
748         m_recent_buffer.step(dtime);
749         m_recent_buffer.deleteByAge(60.0);
750
751         // no need to age messages in anything but m_recent_buffer
752 }
753
754 void ChatBackend::scroll(s32 rows)
755 {
756         m_console_buffer.scroll(rows);
757 }
758
759 void ChatBackend::scrollPageDown()
760 {
761         m_console_buffer.scroll(m_console_buffer.getRows());
762 }
763
764 void ChatBackend::scrollPageUp()
765 {
766         m_console_buffer.scroll(-(s32)m_console_buffer.getRows());
767 }